为什么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 before,它实际上是显示的。
解决方案是在调用showEvent
时也实现调整大小(每次通过调用showEvent
或show()
显示小部件或其顶级父级时都会发生这种情况:
setVisible(True)