我在QtDesigner中创建了一个QGraphicsView。现在我想将mouseMoveEvent连接到它。我知道我必须定义一个继承自QGraphicsView的新类,并覆盖mouseMoveEvent。 Here是一个很好的解释如何做到这一点。
所以我将QtDesigner中的QGraphicsView实例提升为新类floorplanView。我想在我的主python文件main.py中定义这个类,因为它在另一个例子中完成:
import QtGui
class floorplanViewClass(QtGui.QGraphicsView):
moved = pyqtSignal(QMouseEvent)
def __init__(self, parent = None):
super(MyView, self).__init__(parent)
def mouseMoveEvent(self, event):
super(MyView, self).mouseMoveEvent(event)
print "Mouse Pointer is currently hovering at: ", event.pos()
self.moved.emit(event)
我的第一个问题:我必须在Header文件字段中输入什么内容? main.h和main main都给了我:
File "<stdin>", line 1, in <module>
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Oliver/Desktop/pyqt/DRS.py", line 23, in <module>
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
File "C:\Anaconda2\lib\site-packages\PyQt4\uic\__init__.py", line 211, in loadUiType
exec(code_string.getvalue(), ui_globals)
File "<string>", line 1317, in <module>
File "DRS.py", line 23, in <module>
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
File "C:\Anaconda2\lib\site-packages\PyQt4\uic\__init__.py", line 211, in loadUiType
exec(code_string.getvalue(), ui_globals)
File "<string>", line 1317, in <module>
ImportError: cannot import name floorplanViewClass
PyQt是第4版。
答案 0 :(得分:0)
我通过反复试验解决了这个问题:
首先(不是问题的解决方案),myView必须替换为新定义的类的名称。并且pyqtsignal和QMouseEvent必须获取相应的模块名称(我的错):
from PyQt4 import QtCore, QtGui
class floorplanViewClass(QtGui.QGraphicsView):
moved = QtCore.pyqtSignal(QtGui.QMouseEvent)
def __init__(self, parent = None):
super(floorplanViewClass, self).__init__(parent)
def mouseMoveEvent(self, event):
# call the base method to be sure the events are forwarded to the scene
super(floorplanViewClass, self).mouseMoveEvent(event)
print "Mouse Pointer is currently hovering at: ", event.pos()
self.moved.emit(event)
问题的原因是
尚未加载Qt GUIqtCreatorFile = "..."
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
但是,这两行必须位于Application类的定义之上。因此,正确的顺序是:
class floorplanViewClass(QtGui.QGraphicsView):
...
qtCreatorFile = "..." # insert filename of the GUI here
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
...