python - Pyside2 我怎样才能移动盒子?

标签 python python-3.x qgraphicsview qgraphicsitem pyside2

如果我按下左键移动鼠标,我想移动我的 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_())

最佳答案

对于QGraphicsXXXItem,无需覆盖任何方法来启用移动,启用标志QGraphicsItem::ItemIsMovable 就足够了。 .

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

关于python - Pyside2 我怎样才能移动盒子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52311576/

相关文章:

python - 如何解决 python3 的此 pip 错误?

c++ - 使用 openGL 加速时不考虑 QChart z 值?

python - 将 panda 列中的 json 字符串值提取到第一级具有动态键的新列中

Python多线程写日志

Python 3 - 通过循环重建给定集合来减少列表

c++ - 在 qgraphicsview 中忽略 svg 图像透明部分上的鼠标事件?

python - 如何在 QVideoWidget 之上以透明度绘制 QtGraphicsView

python - 如何更改数据框中保存的数据的格式?

python 调用 shell 命令(打开)并等待命令完成。工作完成后如何获得信号?

python - 在 Python 中填写动态在线表单