我想写一个程序,将与QGraphicsView交互。我想在QGraphicsView中收集鼠标和键盘事件。例如,如果用户点击QGraphicsView小部件,我将得到鼠标位置,类似的东西。我可以很容易地对它进行硬编码,但我想使用QtDesigner,因为UI将会频繁更改。pyQt信号/插槽与QtDesigner
这是我对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问题。但每次我回头阅读有关信号和插槽的信息时,它都是有道理的,但我无法得到它。
请大家帮忙,我过去几天一直在b my我的脑袋。我很抱歉,如果这是以前问过,但我已经通过了这个话题的所有主题,我不能得到任何地方。
由于
在你的gui.py文件中,'self.graphicsView = MyForm(graphicsViewWidget)'这一行会抛出一个异常,因为'MyForm'没有被定义。我不确定你在那里的意思。你能修好那条线吗? –
对不起,MyForm应该是QtGui.QGraphicsView。我将它固定在线程中,然后在我的计算机上运行,现在应该可以正常工作。 – Jeff
正如一个建议,如果你使用'从PyQt4.QtGui import *'和'从PyQt4.QtCore import *'导入,你可以删除'QtCore.'和'QtGui.'的所有实例,使代码更具可读性。 – Blender