带QT设计的pyQt信号/插槽

2024-10-01 11:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,将与QGraphicsView交互。我想在QGraphicsView中收集鼠标和键盘事件。例如,如果用户单击QGraphicsView小部件,我将获得鼠标位置,类似于这样。我可以很容易地硬编码它,但是我想使用QtDesigner,因为UI会经常更改。在

这是我的密码图形用户界面.py. 一个简单的小部件,里面有一个QGraphicsView。在

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_graphicsViewWidget(object):
    def setupUi(self, graphicsViewWidget):
        graphicsViewWidget.setObjectName(_fromUtf8("graphicsViewWidget"))
        graphicsViewWidget.resize(400, 300)
        graphicsViewWidget.setMouseTracking(True)
        self.graphicsView = QtGui.QGraphicsView(graphicsViewWidget)
        self.graphicsView.setGeometry(QtCore.QRect(70, 40, 256, 192))
        self.graphicsView.setObjectName(_fromUtf8("graphicsView"))

        self.retranslateUi(graphicsViewWidget)
        QtCore.QMetaObject.connectSlotsByName(graphicsViewWidget)

    def retranslateUi(self, graphicsViewWidget):
        graphicsViewWidget.setWindowTitle(QtGui.QApplication.translate("graphicsViewWidget", "Form", None, QtGui.QApplication.UnicodeUTF8))

程序代码:

^{pr2}$

当我运行这段代码时,它给了我相反的结果。除了在QGraphicsView中,我可以在任何地方都看到鼠标的位置。在

我肯定是我的QObject.connect. 但每次我回去读到信号和插槽的信息时,它都是有意义的,但我不明白。在

请帮帮我,这几天我一直在敲我的头。我很抱歉,如果这是被问到,但我已经通过了所有的线程这个主题,我不能得到任何地方。在

谢谢


Tags: self程序部件def地方鼠标qtguiqapplication
1条回答
网友
1楼 · 发布于 2024-10-01 11:33:29

信号必须来自在ui中定义的QGraphicsView对象。在

您可以创建从QGraphicsView派生的类,如下所示

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyView(QGraphicsView):
    moved = pyqtSignal(QMouseEvent)

    def __init__(self, parent = None):
        super(MyView, self).__init__(parent)

    def mouseMoveEvent(self, event):
        # call the base method to be sure the events are forwarded to the scene
        super(MyView, self).mouseMoveEvent(event)

        print "Mouse Pointer is currently hovering at: ", event.pos()
        self.moved.emit(event)

然后,在设计器中:

  • 右键单击QGraphicsView,然后升级到
  • Promoted class name字段中写入类名(例如“MyView”)
  • 在头文件字段中写入该类所在的文件名,但不包含扩展名.py
  • 单击添加按钮,然后单击升级按钮。在

你可以重新生成你的文件图形用户界面.py和pyuic4。在

相关问题 更多 >