点击图中的鼠标按钮:
self.canvas.Fig.canvas.mpl_connect('button_press_event', self.button_press)
我可以通过打印接收信号并生成答案"按下按钮"在状态栏self.statusBar().showMessage("Key pressed", 400)
但由于某些原因,同一段代码不能用于按键(键盘):
self.canvas.Fig.canvas.mpl_connect('key_press_event', self.key_press)
消息"按键"没有出现,意味着没有发生任何事件或没有收到任何信号。
这是我所有基本课程的MWE:
import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100,data=[[]],timedelay=[],wavelength=[]):
self.Fig = Figure(figsize=(width, height), dpi=dpi)
self.Dataplot = self.Fig.add_subplot(111)
self.compute_initial_figure(data,timedelay, wavelength)
FigureCanvas.__init__(self, self.Fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,QSizePolicy.Expanding,QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self,data,timedelay,wavelength):
pass
class MyStaticMplCanvas(MyMplCanvas):
def __init__(self, *args, **kwargs):
MyMplCanvas.__init__(self, *args, **kwargs)
def compute_initial_figure(self,data,timedelay,wavelength):
self.Dataplot.set_xlabel('Wavelength, nm')
self.Dataplot.set_ylabel('Time delay, ~s')
class GraphView(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.main_widget = QtWidgets.QWidget(self)
self.canvas = MyStaticMplCanvas(self.main_widget, width=8, height=8, dpi=100,data=[[]],timedelay=[],wavelength=[])
self.canvas.Fig.canvas.mpl_connect('key_press_event', self.key_press)
self.canvas.Fig.canvas.mpl_connect('button_press_event', self.button_press)
self.layoutMain = QtWidgets.QHBoxLayout(self.main_widget)
self.layoutFigure = QtWidgets.QHBoxLayout()
self.layoutMain.addLayout(self.layoutFigure)
self.layoutFigure.addWidget(self.canvas)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
def key_press(self,event):
self.statusBar().showMessage("Key pressed", 400)
def button_press(self,event):
self.statusBar().showMessage("Button pressed", 400)
def main():
app = QApplication( sys.argv )
a=GraphView()
a.show()
app.exec()
if __name__ == '__main__':
sys.exit(main())
我的代码有什么问题?
答案 0 :(得分:7)
我找到了解决方案here
后
self.canvas = MyStaticMplCanvas(self.main_widget, width=8, height=8, dpi=100,data=[[]],timedelay=[],wavelength=[])
添加
self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
self.canvas.setFocus()
在画布中单击以使其具有焦点,然后您将看到key_presses
答案 1 :(得分:0)
如果不想每次都想使用键单击画布,则可以执行以下操作,以便在将光标悬停在画布上时焦点自动变为画布。将此添加到您的GraphView.__init__()
:
self.cid_enter = self.canvas.mpl_connect('axes_enter_event', self.on_enter_event)
并将on_enter_event
方法添加到您的GraphView
类中:
def on_enter_event(self, _):
self.canvas.setFocus()
您也无需更改FocusPolicy即可使其工作。
顺便说一句,您不需要做self.canvas.Fig.canvas
来引用画布对象,因为它是圆形的。 self.canvas
已经是画布对象。从理论上讲,您可以无限期地进行self.canvas.Fig.canvas.Fig.canvas
等操作,但仍将引用同一对象。