【问题标题】:QGraphicsGridLayout works in PySide but not PyQt4QGraphicsGridLayout 适用于 PySide 但不适用于 PyQt4
【发布时间】:2014-03-15 04:10:07
【问题描述】:

我一直在努力让QGraphicsGridLayoutPyQt4 合作。我已经安装了PySide,所以我将导入切换到那个以便快速检查,它按预期工作!对于下面的代码,当使用PySide 时,RectangleWidget 上的paint 方法会按预期调用,但是当您使用PyQt4 时,paint 方法永远不会被调用。

我知道RectangleWidget 应该覆盖更多的虚拟方法以实现正确的实现,但我正在剥离一些东西以尝试获取最少的代码来缩小问题范围。

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

感谢任何帮助!我想保持与PyQt4PySide 的兼容性,因此仅继续使用PySide 并不是一个理想的解决方案。谢谢

【问题讨论】:

    标签: python pyqt pyside qgraphicsview


    【解决方案1】:

    QGraphicsGridLayout 拥有添加到其中的项目的所有权(有关详细信息,请参阅docs)。

    在您的示例中,似乎所有 RectangleWidget 项目一旦超出范围就有被垃圾收集的危险。所以如果你给他们一个父母:

        rectangle = RectangleWidget(QtCore.QRectF(0, 0, 50, 50), panel)
    

    一切都会好的。

    【讨论】:

    • 只有 PyQt4 中的 GridLayout 才会发生这种情况有什么特别的原因吗? LinearLayout 在 PyQt4 和 PySide 中运行良好。我现在通常忽略所有权方面,但我想是时候停止忽视它了。谢谢。
    • @D2B。很难说:垃圾收集是不可预测的。这就是为什么忽略所有权可能会有风险。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2020-11-23
    • 2018-09-08
    • 2020-06-26
    相关资源
    最近更新 更多