Moving a QGraphicsItem around a central point in PyQt4

有些话、适合烂在心里 提交于 2019-12-11 22:24:37

问题


I'm using Python 2.7 and PyQt4. I am trying to have a half-circle object that is a QGraphicsItem. I want to be able to move it using the mouse, by clicking and dragging. I can create the object and move it around with the mouse by setting the flag ItemIsMovable. Now the half-circle moves around freely but I want it to move just around the fixed central point. It is difficult to describe, but it should be something similar to a dial. How can I accomplish this?


回答1:


you can use QGraphicsItem::mouseMoveEvent event to track item's movements within the scene and correct its position once it's moved off the restricted area. Pls, check if an example below would work for you:

import sys
from PyQt4 import QtGui, QtCore

class TestEclipseItem(QtGui.QGraphicsEllipseItem):
    def __init__(self, parent=None):
        QtGui.QGraphicsPixmapItem.__init__(self, parent)

        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)

        # set move restriction rect for the item
        self.move_restrict_rect = QtCore.QRectF(20, 20, 200, 200)
        # set item's rectangle
        self.setRect(QtCore.QRectF(50, 50, 50, 50))

    def mouseMoveEvent(self, event):
        # check of mouse moved within the restricted area for the item 
        if self.move_restrict_rect.contains(event.scenePos()):
            QtGui.QGraphicsEllipseItem.mouseMoveEvent(self, event)

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        scene = QtGui.QGraphicsScene(-50, -50, 600, 600)

        ellipseItem = TestEclipseItem()
        scene.addItem(ellipseItem)

        view = QtGui.QGraphicsView()
        view.setScene(scene)
        view.setGeometry(QtCore.QRect(0, 0, 400, 200))
        self.setCentralWidget(view)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

hope this helps, regards



来源:https://stackoverflow.com/questions/5207305/moving-a-qgraphicsitem-around-a-central-point-in-pyqt4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!