Pyside2如何移动箱子?

2024-09-28 21:52:53 发布

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

我想移动我的SimpleItem对象,如果我移动鼠标按左键。我已经成功地获得了鼠标光标的位置,如果我按下对象。但我不知道如何将物品移到那个位置。你能帮帮我吗?在

import sys
from PySide2 import QtGui, QtWidgets, QtCore


class SimpleItem(QtWidgets.QGraphicsItem):
    def __init__(self):
        QtWidgets.QGraphicsItem.__init__(self)
        self.location = 1.0

    def boundingRect(self):
        penWidth = 1.0
        return QtCore.QRectF(-10 - penWidth / 2, -10 - penWidth / 2,
                      20 + penWidth, 20 + penWidth)

    def paint(self, painter, option, widget):
        rect = self.boundingRect()
        painter.drawRect(rect)

    def mousePressEvent(self, event):
        print("hello")

    def mouseMoveEvent(self, event):
        print(event.pos())


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    scene = QtWidgets.QGraphicsScene()
    item = SimpleItem()
    scene.addItem(item)
    view = QtWidgets.QGraphicsView(scene)
    view.show()
    sys.exit(app.exec_())

Tags: 对象importselfeventinitdefsys鼠标
1条回答
网友
1楼 · 发布于 2024-09-28 21:52:53

在qgraphicsx24item的情况下,不必重写任何启用移动的方法,只需启用标志^{}。在

import sys
from PySide2 import QtGui, QtWidgets, QtCore


class SimpleItem(QtWidgets.QGraphicsItem):
    def __init__(self):
        QtWidgets.QGraphicsItem.__init__(self)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)

    def boundingRect(self):
        penWidth = 1.0
        return QtCore.QRectF(-10 - penWidth / 2, -10 - penWidth / 2,
                      20 + penWidth, 20 + penWidth)

    def paint(self, painter, option, widget):
        rect = self.boundingRect()
        painter.drawRect(rect)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    scene = QtWidgets.QGraphicsScene()
    item = SimpleItem()
    scene.addItem(item)
    view = QtWidgets.QGraphicsView(scene)
    view.show()
    sys.exit(app.exec_())

相关问题 更多 >