我正在尝试编写一个与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存在问题。但每次我回去阅读有关信号和插槽的信息都是有意义的,但我无法理解。
请帮忙,我过去几天一直在敲打我的脑袋。我很抱歉,如果以前曾经问过这个问题,但是我已经完成了这个主题的所有主题,我无法到达任何地方。
由于
答案 0 :(得分:3)
信号必须来自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
,然后提升 您可以使用pyuic4重新生成 gui.py 文件。