Pyside2 How can i move box?

后端 未结 1 580
无人共我
无人共我 2021-01-20 12:29

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

相关标签:
1条回答
  • 2021-01-20 13:20

    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_())
    
    0 讨论(0)
提交回复
热议问题