gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:04:10 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com