在 PyQt4 中围绕中心点移动 QGraphicsItem [英] Moving a QGraphicsItem around a central point in PyQt4

查看:46
本文介绍了在 PyQt4 中围绕中心点移动 QGraphicsItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 2.7 和 PyQt4.我试图有一个 QGraphicsItem 的半圆对象.我希望能够通过单击和拖动使用鼠标移动它.我可以通过设置标志 ItemIsMovable 来创建对象并用鼠标移动它.现在半圆自由移动,但我希望它围绕固定的中心点移动.很难描述,但它应该是类似于表盘的东西.我怎样才能做到这一点?

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?

推荐答案

您可以使用 QGraphicsItem::mouseMoveEvent 事件,用于跟踪项目在场景中的移动并在其移出限制区域后更正其位置.请检查以下示例是否适合您:

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

这篇关于在 PyQt4 中围绕中心点移动 QGraphicsItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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