我正在尝试编写一个与 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 的问题。但是每次我回去阅读有关信号和插槽的信息时,它都是有道理的,但我无法理解。
请帮忙,这几天我一直在敲我的头。如果之前有人问过这个问题,我很抱歉,但我已经阅读了有关该主题的所有主题,但我无处可去。
谢谢