【发布时间】:2017-04-10 23:08:27
【问题描述】:
关于这个问题和答案here,当鼠标位于地块上时,有没有办法将滚轮滚动事件传递给滚动条?我尝试在 Main Widget 中使用事件过滤器,但它没有注册轮子在 Main 中滚动,仅在画布/绘图中。我不需要绘图知道它正在滚动,只需要 GUI。任何帮助将不胜感激,谢谢。
【问题讨论】:
标签: python matplotlib pyqt4
关于这个问题和答案here,当鼠标位于地块上时,有没有办法将滚轮滚动事件传递给滚动条?我尝试在 Main Widget 中使用事件过滤器,但它没有注册轮子在 Main 中滚动,仅在画布/绘图中。我不需要绘图知道它正在滚动,只需要 GUI。任何帮助将不胜感激,谢谢。
【问题讨论】:
标签: python matplotlib pyqt4
在 PyQt 中滚动 QScrollArea 内的 FigureCanvas 的一种解决方案是使用 matplotlib 的 "scroll_event"(参见 Event handling tutorial)并将其连接到滚动 QScrollArea 的滚动条的函数。
示例(来自我对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)
【讨论】: