PyQt/PySide How to access/move QGraphicsItem after having added it to QGraphicsScene

天大地大妈咪最大 提交于 2019-12-11 01:42:19

问题


This might be a very uninformed question.

I've been trying to figure out QGraphics*, and have run into a problem when trying to move an item (a pixmap) relative to or inside of the 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())  

This is the relevant part of the program with an arbitrary PNG

My goal, for example, would be to move the trash-can to the left-most part of the QGraphicsView.

I tried appending this to the code above:

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

However, it doesn't make a difference, and even if it did, it would be awkward to have to search for it with a "for in".

So my questions are:

  1. How do I access a QPixmap item once I have added it to a QGraphicsView via a QGraphicsScene. (I believe The QPixmap is at this point a QGraphicsItem, or more precisely a QGraphicsPixmapItem.)

  2. Once accessed, how do I move it, or change any of its other attributes.

Would be very grateful for help, or if anyone has any good links to tutorials relevant to the question. :)


回答1:


The problem is that you need to set the size of your scene and then set positions of the items, check this example:

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


来源:https://stackoverflow.com/questions/21531620/pyqt-pyside-how-to-access-move-qgraphicsitem-after-having-added-it-to-qgraphicss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!