Search code examples
pythonpyqtpyqt5qgraphicsviewqgraphicsscene

Fit QGraphisItem in view


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

Solution

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