如何收集用pyqt5绘制的matplotlib画布中最后一次鼠标点击的轴对象



我有一个交互式窗口,我需要知道在交互过程中选择了哪个子地块。当我单独使用matplotlib时,我可以使用plt.connect('button_press_event', myMethod)。但对于pyqt5,我正在导入FigureCanvasQTAgg,并且有对图形本身的引用,但不是pyplot的等价物。因此,我无法创建该引用。

最小可重复性示例:

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
import numpy as np
# list to store the axis last used with a mouseclick
currAx = []

# detect the currently modified axis
def onClick(event):
if event.inaxes:
currAx[:] = [event.inaxes]

class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.canvas = FigureCanvas(plt.Figure())
self.axis = self.canvas.figure.subplots(3)
for i, ax in enumerate(self.axis):
t = np.linspace(-i, i + 1, 100)
ax.plot(t, np.sin(2 * np.pi * t))
self.listOfSpans = [SpanSelector(
ax,
self.onselect,
"horizontal"
)
for ax in self.axis]
plt.connect('button_press_event', onClick)
# need an equivalent of ^^ to find the axis interacted with
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
toolbar = NavigationToolbar(self.canvas, self)
layout.addWidget(toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
self.show()
def onselect(self, xmin, xmax):
if xmin == xmax:
return
# identify the axis interacted and do something with that information
for ax, span in zip(self.axis, self.listOfSpans):
if ax == currAx[0]:
print(ax)
print(xmin, xmax)
self.canvas.draw()

def run():
app = QApplication([])
mw = MyWidget()
app.exec_()

if __name__ == '__main__':
run()

显然,还有一种连接画布的方法——canvas.mpl_connect('button_press_event', onclick)

链接到解释:https://matplotlib.org/stable/users/explain/event_handling.html

在该链接中找到了指向解释的链接:在matplotlib中用子图而不是图形控制鼠标单击事件。

相关内容

  • 没有找到相关文章

最新更新