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

2024-06-02 06:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我创建了一个scene子类来管理将在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)

Tags: selfeventuiinit部件defpositionscene
1条回答
网友
1楼 · 发布于 2024-06-02 06:46:31

使用addItem(your_pixmap_object)QPixmap添加到场景中。然后,您可以在返回的QGraphicsItem上使用setPos(...)(当您使用addItem(...)并且成功地将项目插入到场景中时,将返回此值)。在

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

如果您想使用QGraphicsPixmapItem,过程与上面的过程相同,但只需使用self.addPixmap(...),就像您在代码中所做的那样。在

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

相关问题 更多 >