QGraphicsView.fitInView()未按预期工作

2024-07-08 09:36:07 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么QGraphicsView.fitInView()只有在我调整窗口大小后才能工作

我正在MS Windows 10上使用Python 2.7.7和Qt 4.8.7。下面是演示该问题的代码

感谢您分享您的见解和帮助。 奥拉夫

import sys

from PyQt4 import QtCore
from PyQt4 import QtGui


class Test(QtGui.QWidget):
    def __init__(self, *args):
        super(Test, self).__init__(*args)

        self.setObjectName("Form")
        self.resize(200, 100)
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)

        deltaX = 40
        deltaY = 40
        width = 200 - deltaX
        height = 200 - deltaY

        print 'constructor start'
        scene = QtGui.QGraphicsScene(self)
        for i in range(5):
            scene.addLine(0, i*deltaY, width, i*deltaY)
            scene.addLine(i*deltaX, 0, i*deltaX, height)
        self.graphicsView.setScene(scene)
        self.graphicsView.fitInView(scene.sceneRect(), QtCore.Qt.KeepAspectRatio)
        print 'constructor end'

    def resizeEvent(self, event):
        print 'resize event start'
        scene = self.graphicsView.scene()
        r = scene.sceneRect()
        print '  rect %d %d %d %d' % (r.x(), r.y(), r.width(), r.height())
        self.graphicsView.fitInView(r, QtCore.Qt.KeepAspectRatio)
        print 'resize event end'

if __name__ == '__main__':
    a = QtGui.QApplication(sys.argv)
    w = Test()
    a.setActiveWindow(w)
    w.show()
    a.exec_()

Tags: testimportselfsceneqtprintresizeqtgui
1条回答
网友
1楼 · 发布于 2024-07-08 09:36:07

当一个小部件首次初始化时,它(通常,但这取决于很多事情)在实际显示之前收到一个resizeEvent

解决方案是在调用^{}时也实现调整大小(每次通过调用show()setVisible(True)显示小部件或其顶级父级时都会发生这种情况):

    def updateView(self):
        scene = self.graphicsView.scene()
        r = scene.sceneRect()
        print '  rect %d %d %d %d' % (r.x(), r.y(), r.width(), r.height())
        self.graphicsView.fitInView(r, QtCore.Qt.KeepAspectRatio)

    def resizeEvent(self, event):
        print 'resize event start'
        self.updateView()
        print 'resize event end'

    def showEvent(self, event):
        # ensure that the update only happens when showing the window
        # programmatically, otherwise it also happen when unminimizing the
        # window or changing virtual desktop
        if not event.spontaneous():
            print 'show event'
            self.updateView()

相关问题 更多 >

    热门问题