我有一个在matplotlib中设计的图表,并在python 2.7中使用QT显示。我想连接两个听众:
过去早些时候,我使用的是普通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_())
我想在上面的代码中添加listers。非常感谢。
答案 0 :(得分:1)
对于这种情况,您必须使用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)