I've been trying for hours to get QGraphicsGridLayout
to work with PyQt4
. I have PySide
installed so I switched the imports to that for a quick check and it worked as expected! For the code below, when PySide
is used, the paint
method on the RectangleWidget
is called as expected but when you use PyQt4
the paint
method is never called.
I know that the RectangleWidget
should override some more virtual methods for a proper implementation but I was stripping things out to try and get the minimal amount of code to narrow down the problem.
from PySide import QtGui, QtCore
# from PyQt4 import QtGui, QtCore
class RectangleWidget(QtGui.QGraphicsWidget):
def __init__(self, rect, parent=None):
super(RectangleWidget, self).__init__(parent)
self.rect = rect
def paint(self, painter, *args, **kwargs):
print('Paint Called')
painter.drawRect(self.rect)
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QtGui.QWidget(self)
central_layout = QtGui.QHBoxLayout()
self.central_widget.setLayout(central_layout)
self.setCentralWidget(self.central_widget)
self.resize(500, 500)
self.view = QtGui.QGraphicsView()
self.scene = QtGui.QGraphicsScene()
self.view.setScene(self.scene)
panel = QtGui.QGraphicsWidget()
self.scene.addItem(panel)
layout = QtGui.QGraphicsGridLayout()
panel.setLayout(layout)
for i in range(4):
for j in range(4):
rectangle = RectangleWidget(QtCore.QRectF(0, 0, 50, 50))
layout.addItem(rectangle, i, j)
central_layout.addWidget(self.view)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
widget = MainWindow()
widget.show()
app.exec_()
Any help is appreciated! I would like to maintain compatibility with both PyQt4
and PySide
so continuing using PySide
only is not really an ideal solution. Thanks
The QGraphicsGridLayout
takes ownership of the items added to it (see the docs for further details).
In your example, it would seem that all the RectangleWidget
items are in danger of being garbage-collected once they go out of scope. So if you give them a parent:
rectangle = RectangleWidget(QtCore.QRectF(0, 0, 50, 50), panel)
all should be well.