1

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Vesa95
  • 607
  • 1
  • 7
  • 26

1 Answers1

4

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • It's work but I have a question, why dis you make a function "setPixmap" and above it you call: self.m_pixmap_item = self.scene().addPixmap(QtGui.QPixmap())? – Vesa95 Jun 07 '19 at 07:18
  • 1
    @Vesa95 Conceptually I understood that you only want to show an image so it is not necessary to export scene out of the class. So consider placing an item with an empty pixmap and the function will change only that pixmap. Do you know what the classes are for and their design? review some UML and concepts related to SW design. – eyllanesc Jun 07 '19 at 07:25
  • now after your explanation I think I understood! Thank you a lot! – Vesa95 Jun 07 '19 at 10:44