簡體   English   中英

Pyside2我如何移動盒子?

[英]Pyside2 How can i move box?

如果要移動鼠標左鍵,我想移動我的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_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM