pyqt4 scrollArea事件和matplotlib wheelEvent

时间:2017-04-10 23:08:27

标签: python matplotlib pyqt4

关于这个问题和答案here,当鼠标位于图上时,有没有办法将滚轮滚动事件传递给滚动条?我已经尝试在主窗口小部件中使用事件过滤器,但它没有注册到轮子在Main中滚动,只在canvas / plot中滚动。我不需要知道它正在滚动,只有GUI。非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

在PyQt中滚动FigureCanvas内的QScrollArea的一个解决方案是使用matplotlib' s "scroll_event"(请参阅Event handling tutorial)并将其连接到一个函数滚动QScrollArea的scrollBar。

示例(来自我对this question的回答)可以扩展为通过

连接到函数scrolling
self.canvas.mpl_connect("scroll_event", self.scrolling)

在此函数内部,滚动条值会更新。

import matplotlib.pyplot as plt
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar

class ScrollableWindow(QtGui.QMainWindow):
    def __init__(self, fig):
        self.qapp = QtGui.QApplication([])

        QtGui.QMainWindow.__init__(self)
        self.widget = QtGui.QWidget()
        self.setCentralWidget(self.widget)
        self.widget.setLayout(QtGui.QVBoxLayout())
        self.widget.layout().setContentsMargins(0,0,0,0)
        self.widget.layout().setSpacing(0)

        self.fig = fig
        self.canvas = FigureCanvas(self.fig)
        self.canvas.draw()
        self.scroll = QtGui.QScrollArea(self.widget)
        self.scroll.setWidget(self.canvas)

        self.nav = NavigationToolbar(self.canvas, self.widget)
        self.widget.layout().addWidget(self.nav)
        self.widget.layout().addWidget(self.scroll)

        self.canvas.mpl_connect("scroll_event", self.scrolling)

        self.show()
        exit(self.qapp.exec_())

    def scrolling(self, event):
        val = self.scroll.verticalScrollBar().value()
        if event.button =="down":
            self.scroll.verticalScrollBar().setValue(val+100)
        else:
            self.scroll.verticalScrollBar().setValue(val-100)


# create a figure and some subplots
fig, axes = plt.subplots(ncols=4, nrows=5, figsize=(16,16))
for ax in axes.flatten():
    ax.plot([2,3,5,1])

# pass the figure to the custom window
a = ScrollableWindow(fig)