python - 使 QGraphisItem 适合 View

标签 python pyqt pyqt5 qgraphicsview qgraphicsscene

是一种适合 View 中任何图像(我在 QPixmap 中导入)并保持宽高比的方法>。我尝试了很多解决方案,但没有一个有效。 我也不确定我需要适应什么? QGraphicsView 中的 QGraphicsScene?或者 QGraphicsView 中的 QPixmap?

from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)

        scene = QtWidgets.QGraphicsScene()
        self.setScene(scene)




if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    photo = QtGui.QPixmap("image.jpg")
    w.scene().addPixmap(photo)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

最佳答案

你必须在QGraphicsView的resizeEvent()方法中使用QGraphicsView的fitInView()方法:

from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        self.setScene(scene)
        self.m_pixmap_item = self.scene().addPixmap(QtGui.QPixmap())

    def setPixmap(self, pixmap):
        self.m_pixmap_item.setPixmap(pixmap)

    def resizeEvent(self, event):
        if not self.m_pixmap_item.pixmap().isNull():
            self.fitInView(self.m_pixmap_item, QtCore.Qt.KeepAspectRatio)
        super(GraphicsView, self).resizeEvent(event)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    photo = QtGui.QPixmap("image.jpg")
    w.setPixmap(photo)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

关于python - 使 QGraphisItem 适合 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56488773/

相关文章:

python - 在 Python 中使用 QT Designer (.ui) 文件时如何启用 QDropEvent?

python-3.5 - ImportError: DLL 加载失败: 找不到指定的模块。无法执行脚本pyi_rth_qt5plugins

python - PyQt5加载网页内容时返回None值

python - 在Python中检索数组中匹配条件的所有元素

python - 返回所有可能的 DNA 组合

python - 基于 Python 中的字典/列表标记单词

python - pyqt QObject : Cannot create children for a parent that is in a different thread

python - 没有名为 PyQt5.sip 的模块

python - 如何从异步请求应用程序引擎中的RPC对象获取响应URL?

linux - Python 3.6; PyQt5;架构Linux;被信号 6 : SIGABRT 中断