【问题标题】:Connect mouseMoveEvent to widget by creating a subclass通过创建子类将 mouseMoveEvent 连接到小部件
【发布时间】:2023-12-23 02:10:01
【问题描述】:

我在 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)

我的第一个问题:我必须在头文件字段中输入什么? main.h 和 just 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 版。

【问题讨论】:

    标签: python pyqt pyqt4


    【解决方案1】:

    我通过反复试验解决了这个问题:

    首先(不是问题的解决方案),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 GUI还没有被加载

    qtCreatorFile = "..."
    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):
        ...
    

    【讨论】: