简体   繁体   English

Pyside2我如何移动盒子?

[英]Pyside2 How can i move box?

I want to move my SimpleItem object if I move mouse pressing left button. 如果要移动鼠标左键,我想移动我的SimpleItem对象。 I have successed getting the position of mouse cursor if I press the object. 如果按下对象,我已经成功获取了鼠标光标的位置。 but I have no idea how to move the item to that position. 但是我不知道如何将物品移动到那个位置。 Could you help me? 你可以帮帮我吗?

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

In the case of the QGraphicsXXXItem it is not necessary to overwrite any method to enable the movement, it is enough to enable the flag QGraphicsItem::ItemIsMovable . 对于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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM