在视图中适合 QGraphisItem [英] Fit QGraphisItem in view

查看:67
本文介绍了在视图中适合 QGraphisItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一种适合任何图像(我在 QPixmap 中导入)并保持纵横比的方法>.我尝试了很多解决方案,但没有一个.另外我不确定我需要适合什么?QGraphicsView 中的 QGraphicsScene?还是 QGraphicsView 中的 QPixmap?

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

推荐答案

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

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

这篇关于在视图中适合 QGraphisItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆