【问题标题】:PyQt/PySide How to access/move QGraphicsItem after having added it to QGraphicsScenePyQt/PySide 将 QGraphicsItem 添加到 QGraphicsScene 后如何访问/移动它
【发布时间】:2014-02-27 04:34:30
【问题描述】:

这可能是一个非常无知的问题。

我一直在尝试找出QGraphics*,但在尝试相对于QGraphicsView 或在QGraphicsView 内部移动项目(像素图)时遇到了问题。

class MainWindow(QMainWindow,myProgram.Ui_MainWindow):

    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.scene = QGraphicsScene()
        self.graphicsView.setScene(self.scene)

        pic = QPixmap('myPic.png')

        self.scene.addPixmap(pic)

        print(self.scene.items())  

这是程序的相关部分,带有任意 PNG

例如,我的目标是将垃圾桶移动到QGraphicsView 的最左侧。

我尝试将其附加到上面的代码中:

   pics = self.scene.items()
    for i in pics:
        i.setPos(100,100)

但是,这并没有什么不同,即使有,也不得不用“for in”搜索它会很尴尬。

所以我的问题是:

  1. 通过QGraphicsSceneQPixmap 项目添加到QGraphicsView 后,如何访问它。 (我相信QPixmap此时是QGraphicsItem,或者更准确地说是QGraphicsPixmapItem。)

  2. 访问后,如何移动它或更改它的任何其他属性。

非常感谢您的帮助,或者如果有人有任何与该问题相关的教程的良好链接。 :)

【问题讨论】:

    标签: python-3.x pyside qgraphicsview qgraphicsitem qgraphicsscene


    【解决方案1】:

    问题是您需要设置场景的大小,然后设置项目的位置,请查看此示例:

    from PyQt4 import QtGui as gui
    
    app = gui.QApplication([])
    
    pm = gui.QPixmap("icon.png")
    
    scene = gui.QGraphicsScene()
    scene.setSceneRect(0, 0, 200, 100) #set the size of the scene
    
    view = gui.QGraphicsView()
    view.setScene(scene)
    
    item1 = scene.addPixmap(pm) #you get a reference of the item just added
    item1.setPos(0,100-item1.boundingRect().height()) #now sets the position
    
    view.show()
    app.exec_()
    

    【讨论】:

    • 这很有意义!谢谢!
    • 你知道糟糕的是我在过去 20 分钟左右编写了一段代码来演示这个问题,所以我可以来这里问一个非常相似的问题,因为我也有同样的问题问题只是找到解决问题的这个问题。所以我要去删除我制作的所有代码。感谢您的解决方案!!!
    猜你喜欢
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2019-03-14
    相关资源
    最近更新 更多