Skip to main content
 首页 » 编程设计

python之子类化 QGraphicsLayoutItem 以显示像素图

2024年11月01日11www_RR

我试图将 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() 方法没有被调用,我 最终得到一个超白的乳白色图形 View 。

亲爱的 Qt 科学家,我如何实现这一目标。

请您参考如下方法:

graphicsItem 不是虚拟的。这就是 Qt 不调用它的原因。看来您需要在构造函数中调用 setGraphicsItem 并从类中删除 graphicsItem 和 setGraphicsItem 方法。重新实现非虚函数没有任何意义。