使用QGraphicsLayoutItem子类来显示像素图

3
我试图将QGraphicsPixmapItem放入QGraphicsLinearLayout中。由于QGraphicsPixmapItem不是QGraphicsLayoutItem,所以这是不可能的。因此,我试图对后者进行子类化,并使其像一个像素图项一样工作。
以下是我的失败尝试:
from PySide import QtGui, QtCore
import sys

class MyItem(QtGui.QGraphicsLayoutItem):
  def __init__(self, image, parent=None):
    super().__init__(parent)
    self.gitem = QtGui.QGraphicsPixmapItem()
    self.gitem.setPixmap(QtGui.QPixmap(image))

  def sizeHint(which, constraint, other):
    return QtCore.QSizeF(200, 200)

  def setGeometry(self, rect):
    self.gitem.setPos(rect.topLeft())

  def graphicsItem(self):
    #does not get called
    return self.gitem

def setGraphicsItem(self, item):
    self.gitem = item

class Application(QtGui.QGraphicsView):
  def __init__(self, parent=None):
    super().__init__(parent)
    gwidget = QtGui.QGraphicsWidget()
    layout = QtGui.QGraphicsLinearLayout()
    layout.addItem(MyItem(r'C:\image1.jpg'))
    layout.addItem(MyItem(r'C:\image2.jpg'))
    gwidget.setLayout(layout)
    scene = QtGui.QGraphicsScene()
    scene.addItem(gwidget)
    self.setScene(scene)

app = QtGui.QApplication(sys.argv)
main = Application()
main.show()
sys.exit(app.exec_())

从评论中可以看出,graphicsItem() 方法并未被调用,最终导致我的图形视图呈现异常白色。

亲爱的 Qt 科学家们,请问我该如何解决这个问题?

1个回答

2

graphicsItem 不是虚函数,所以 Qt 不会调用它。看起来你需要在构造函数中调用 setGraphicsItem 并从你的类中移除 graphicsItemsetGraphicsItem 方法。重新实现非虚函数没有任何意义。


调用构造函数中的 setGraphicsItem 会改变什么?如果不调用 graphicsItem,系统如何知道类所代表的项?在 setGraphicsItem 中是否需要进行特殊的魔法操作? - MadeOfAir
1
系统调用graphicsItem()的默认实现,该实现返回先前使用setGraphicsItem的默认实现设置的项。只需调用self.setGraphicsItem(self.gitem)即可。 - Pavel Strakhov
好的。我刚刚移除了 setGraphicsItemgraphicsItem,按照你说的做了一下,看起来可以了。非常感谢。 - MadeOfAir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接