gpt4 book ai didi

python - QGraphicsView.fitInView() 未按预期工作

转载 作者:行者123 更新时间:2023-12-02 19:30:28 32 4
gpt4 key购买 nike

为什么 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_()

最佳答案

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

解决方案是在 showEvent 时也实现调整大小被调用(每次通过调用 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()

关于python - QGraphicsView.fitInView() 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61886358/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com