Python matplotlib和Qt:鼠标滚动事件键始终为“无”

Python matplotlib和Qt:鼠标滚动事件键始终为“无”,python,pyqt4,Python,Pyqt4,现在已经修复了 我正在尝试使用带有嵌入式matplotlib画布的PyQt4制作GUI。当我将光标滚动到画布上时,我希望能够根据额外的按键控制行为(本例中为控制)。但是,链接到“scroll_事件”的mouseEvent的key属性始终为None。我测试了我的代码是否正确注册了“button\u press\u事件”生成的mouseEvent的键。 在下面的示例中,按下on_press方法可正确打印同时按下的键。而scoll上的始终不打印任何内容 如何访问鼠标滚动事件期间按下的键 提前谢谢 im

现在已经修复了

我正在尝试使用带有嵌入式matplotlib画布的PyQt4制作GUI。当我将光标滚动到画布上时,我希望能够根据额外的按键控制行为(本例中为控制)。但是,链接到“scroll_事件”的mouseEvent的key属性始终为None。我测试了我的代码是否正确注册了“button\u press\u事件”生成的mouseEvent的键。 在下面的示例中,按下
on_press
方法可正确打印同时按下的键。而scoll上的
始终不打印任何内容

如何访问鼠标滚动事件期间按下的键

提前谢谢

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

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


class GraphicTool(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.create_menu()


    def on_press(self, event):
        print event.key

    def on_scroll(self, event):
        print event.key
        if event.key == 'ctrl':
            # do something
            pass
        else:
            # do something else
            pass

    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 10x8 inches, 100 dots-per-inch
        self.dpi = 100
        self.fig = Figure((10.0, 8.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.canvas.setFocusPolicy(Qt.ClickFocus)
        self.canvas.setFocus()

        self.axes = self.fig.add_subplot(111)
        self.canvas.mpl_connect('scroll_event', self.on_scroll)
        self.canvas.mpl_connect('button_press_event', self.on_press)

        # Create the navigation toolbar, tied to the canvas
        self.mpl_toolbar = NavigationToolbar(self.canvas,
                                             self.main_frame)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)


def main():
    app = QApplication(sys.argv)
    viewer = GraphicTool()
    viewer.show()
    viewer.raise_()
    app.exec_()

if __name__ == "__main__":
    main()

上面这个简短的例子确实如预期的那样有效。然而,当我把它合并到一个更大的项目中时,它失败了。我将继续调试,以查看是否有任何其他事件干扰滚动事件。

我已检查了您的代码。这是预期的工作

def on_scroll(self, event):
    print event.xdata
    print event.ydata
    print event.key
    if event.key == 'ctrl':
        # do something
        pass
    else:
        # do something else
        pass
这是代码的输出。我刚刚在代码中添加了扩展数据和ydata

0.480977867785
0.57896567718
control
0.480977867785
0.57896567718
shift
0.480977867785
0.57896567718
shift

我的现在也能用了。不知道其间发生了什么。对不起!