如何在 QtGraphicsView/QtGraphicsScene (PyQt4) 中的某个位置放置图像?

How to place an image at a certain position in QtGraphicsView/QtGraphicsScene (PyQt4)?

我正在使用 Qt Designer 和 PyQt4 创建一个应用程序。我想知道如何将图像添加到 QtGraphicsView 小部件到我想要的位置。 例如,当我单击 QtGraphicsView 小部件时,我想将图像添加到该确切位置。我在网上搜索过,但找不到任何有帮助的东西。

我创建了一个场景子类来管理将在 QtGraphicsView 小部件中显示的项目。我能够获得我点击的位置的坐标,但我不知道如何将项目放置在该特定位置。下面是我的代码:

class graphicsScene(QtGui.QGraphicsScene):
    def __init__(self, parent=None):
        super(graphicsScene, self).__init__(parent)

    def mousePressEvent(self, event):
        position = QtCore.QPointF(event.scenePos())
        pixmap = QtGui.QPixmap("host.png")
        pixmap_scaled = pixmap.scaled(30, 30,    QtCore.Qt.KeepAspectRatio)
        self.itemAt(pixmap_scaled,position.x(),position.y())

        self.addPixmap(pixmap_scaled)
        print "pressed here: " + str(position.x()) + ", " + str(position.y())
        self.update()


    def mouseReleaseEvent(self, event):
        position = QtCore.QPointF(event.scenePos())
        print "released here: " + str(position.x()) + ", " + str(position.y())
        self.update()

class form(QtGui.QMainWindow):
    def __init__(self):
        super(mininetGUI, self).__init__()
        self.ui = uic.loadUi('form.ui')

        self.scene = graphicsScene()
        self.ui.view.setScene(self.scene)

使用addItem(your_pixmap_object)QPixmap添加到场景中。然后你可以在返回的 QGraphicsItem 上使用 setPos(...) (当你使用 addItem(...) 并且项目插入场景成功时返回)。你传递给你的点 setPos(...) 将是事件的一部分(正如您已经通过调用 event.scenePos() 所做的那样)。

pixmap = QPixmap(...)
sceneItem = self.addItem(pixmap)
sceneItem.setPos(event.scenePos())

如果您想使用 QGraphicsPixmapItem,步骤与上述相同,但只需像您在代码中所做的那样使用 self.addPixmap(...)

除了放置项目之外,您可能还需要处理一件事 - 按下鼠标按钮,将光标移动到场景中的其他位置,同时仍然按下按钮,然后释放它。这会将项目插入到移动事件的起始位置(同时按下按钮并移动),但这可能不是您想要的。您必须考虑在 mouseReleaseEvent(...) 中处理插入是否会更好。这实际上取决于您希望在这种特定情况下如何工作。