Pyside2 如何移动盒子? [英] Pyside2 How can i move box?

查看:79
本文介绍了Pyside2 如何移动盒子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我按下左键移动鼠标,我想移动我的 SimpleItem 对象.如果我按下对象,我已成功获取鼠标光标的位置.但我不知道如何将项目移动到该位置.你能帮我吗?

I want to move my SimpleItem object if I move mouse pressing left button. 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_())

推荐答案

QGraphicsXXXItem的情况下不需要覆盖任何方法来启用移动,启用标志就足够了QGraphicsItem::ItemIsMovable.

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.

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

这篇关于Pyside2 如何移动盒子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆