我正在尝试编写一个与QGraphicsView交互的程序。我想在QGraphicsView中发生鼠标和键盘事件时收集它们。例如,如果用户单击QGraphicsView小部件,则会获取鼠标位置之类的内容。我可以很容易地硬编码实现它,但我想使用QtDesigner,因为UI将经常更改。
这是gui.py的代码。其中包含一个简单的小部件,其中有一个QGraphicsView。
程序的代码如下:
当我运行这段代码时,结果与我想要的相反。我得到了鼠标位置,除了在QGraphicsView内部。
我确定这是我的QObject.connect有问题。但每次我回去阅读信号和槽的相关知识时,它都很合理,但我却无法理解。
请帮忙,我已经纠结了几天了。如果以前问过这个问题,我很抱歉,但我已经查看了所有关于此主题的线程,但无济于事。
谢谢
这是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有问题。但每次我回去阅读信号和槽的相关知识时,它都很合理,但我却无法理解。
请帮忙,我已经纠结了几天了。如果以前问过这个问题,我很抱歉,但我已经查看了所有关于此主题的线程,但无济于事。
谢谢
self.graphicsView = MyForm(graphicsViewWidget)
这一行会抛出异常,因为MyForm
未定义。我不确定你的意思是什么。你能修复这一行吗? - Stephen Terryfrom PyQt4.QtGui import *
和from PyQt4.QtCore import *
导入,您可以删除所有QtCore.
和QtGui.
的实例,使代码更易读。 - Blender