Fit QGraphisItem in view

人盡茶涼 提交于 2020-06-09 02:59:09

问题


Is a method to fit any image in view (that I import in QPixmap) and keep aspect ratio>. I try many solution but non of those works. Also I don't not sure what I need to fit? QGraphicsScene in QGraphicsView? Or QPixmap in QGraphicsView?

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_())

回答1:


You have to use the fitInView() method of QGraphicsView in the resizeEvent() method of QGraphicsView:

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_())


来源:https://stackoverflow.com/questions/56488773/fit-qgraphisitem-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!