我正在尝试编写一个将与QGraphicsView交互的程序.我想在QGraphicsView中收集鼠标和键盘事件.例如,如果用户单击QGraphicsView小部件,我将获得鼠标位置,类似这样.我可以很容易地对其进行硬编码,但是我想使用QtDesigner,因为UI会经常更改.
这是我为gui.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))
该程序的代码:
#!/usr/bin/python -d
import sys
from PyQt4 import QtCore, QtGui
from gui import Ui_graphicsViewWidget
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_graphicsViewWidget()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.graphicsView, QtCore.SIGNAL("moved"), self.test)
def mouseMoveEvent(self, event):
print "Mouse Pointer is currently hovering at: ", event.pos()
self.emit(QtCore.SIGNAL("moved"), event)
def test(self, event):
print('in test')
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
当我运行这段代码时,它给了我与我想要的相反的东西.除了在QGraphicsView内部,我到处都可以看到鼠标的位置.
我确定这是我的QObject.connect的问题.但是每次我回过头来阅读有关信号和插槽的信息时,这都是有道理的,但我却听不懂.
请帮忙,这几天来我一直在head头.很抱歉,是否如以前所要求的那样,但是我已经遍历了有关此主题的所有主题,因此无处可寻.
谢谢
解决方法:
信号必须来自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,然后升级到
>在“晋升的班级名称”字段中输入班级名称(例如“ MyView”),
>在“头文件”字段中输入该类的文件名,但不带.py扩展名,
>单击添加按钮,然后单击升级按钮.
您可以使用pyuic4重新生成文件gui.py.