AttributeError: 'QWheelEvent' 对象没有属性 'delta'

mar*_*lli 4 python pyqt pyqt5

我正在使用 pyqt5 制作一个简单的 GUI。它运行良好,但是当我打开它并尝试使用鼠标滚轮时,它崩溃并显示以下错误:

AttributeError: 'QWheelEvent' 对象没有属性 'delta'。

这是重现问题的代码:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import sys

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import matplotlib.pyplot as plt
import numpy as np

class View(QGraphicsView):

    def __init__(self):
        super(View, self).__init__()

        self.setRenderHint(QPainter.Antialiasing)
        self.initScene(5)

    def initScene(self,h):     

        self.scene = QGraphicsScene()
        #self.setSceneRect(0, 100, 1400, 700)  #this controls where the scene begins relative to the window
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setGeometry(0,0,900,700)
        #self.setSceneRect(0, 0, 2607, 700)


        self.figure.subplots_adjust(left=0,right=1,bottom=0,top=1,wspace=0, hspace=0)
        axes1 = self.figure.add_subplot(3, 1, 1)
        axes2 = self.figure.add_subplot(3, 1, 2)
        axes3 = self.figure.add_subplot(3, 1, 3)
        axes1.yaxis.set_ticks([5,6])
        axes1.set_yticklabels([5,6])
        #axes.yaxis.set_offset_position('right')
        axes1.yaxis.set_tick_params(color='red',labelcolor='red',direction='in',labelright = 'on',labelleft='off')
        axes1.plot(np.linspace(0,10,10), np.linspace(0,10,10))
        axes2.plot(np.linspace(0,10,10), np.linspace(0,10,10))
        axes3.plot(np.linspace(0,10,10), np.linspace(0,10,10))
        axes1.spines['bottom'].set_color('red')
        axes2.spines['top'].set_color('red')
        self.canvas.draw()
        self.setScene(self.scene)
        self.scene.addWidget(self.canvas)

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow,self).__init__()

        self.setGeometry(150, 150, 1424, 750) #the first two arguments control where the window will appear on the screen, the next

        self.view = View()
        self.view.setGeometry(0,0,1400,700)
        self.setCentralWidget(self.view)

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec_()
Run Code Online (Sandbox Code Playgroud)

其他可能相关的细节:我将代码保存为 .py 文件,并从“Anaconda Prompt”命令行运行它。

如果我没有将鼠标单击事件连接到任何东西,那么它就不会崩溃,所以我无法理解为什么当我使用鼠标滚轮时它会崩溃(即使没有连接到任何东西)。

Ism*_*sma 5

您正在使用 PyQt5,但随后您为 PyQt4 导入了 matplotlib 后端,所以我想这就是错误的来源。

Qt4的有一个delta类中的属性QWheelEvent,但现在在QT5这是由两个不同的属性替换angleDeltapixelDelta所以这就是为什么你的错误。

要解决它,只需按如下方式替换您的导入(将 4 替换为 5):

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
Run Code Online (Sandbox Code Playgroud)

参考

https://doc-snapshots.qt.io/qt5-dev/qwheelevent.html