在嵌入 matplotlib 的 Qt4 应用程序中连接鼠标事件 canvas

Connect mouse events in a Qt4 application embedding matplotlib canvas

我在 matplotlib 中设计了一个图,并在 python 2.7 中使用 QT 显示。我想将以下两个侦听器连接到它:

  1. button_press_event
  2. motion_notify_event

过去早些时候,我使用的是普通 matplotlib,我曾经按以下方式进行操作:

import matplotlib.pyplot as plt

def mouseClick(event):
    pass

def mouseMove(event):
    pass

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
fig.canvas.draw()

plt.connect('button_press_event', mouseClick)
plt.connect('motion_notify_event', mouseMove)
plt.show()

下面是我完整的QT代码:

import sys
from matplotlib.backends import qt_compat
use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE
if use_pyside:
    from PySide import QtGui, QtCore
else:
    from PyQt4 import QtGui, QtCore

from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.main_widget = QtGui.QWidget(self)
        l = QtGui.QVBoxLayout(self.main_widget)
        sc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(sc)
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("hello")
aw.show()
sys.exit(qApp.exec_())

我想在上面的代码中添加监听器。非常感谢。

对于这种情况,您必须使用来自 FigureCanvas

的 mpl_connect
sc.mpl_connect('button_press_event', self.mouseClick)
sc.mpl_connect('motion_notify_event', self.mouseMove)

代码:

class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.main_widget = QtGui.QWidget(self)
        l = QtGui.QVBoxLayout(self.main_widget)
        sc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(sc)
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        sc.mpl_connect('button_press_event', self.mouseClick)
        sc.mpl_connect('motion_notify_event', self.mouseMove)


    def mouseClick(self, event):
        print(event)

    def mouseMove(self, event):
        print(event)