【发布时间】:2015-10-17 19:56:07
【问题描述】:
通过在图上单击鼠标按钮:
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())
我的代码有什么问题?
【问题讨论】:
-
你说的不起作用是什么意思?代码会产生错误吗?如果是这样,请发布完整的跟踪。
-
另外,提供的代码不能在我的机器上运行,在你的 app.exec() 行产生无效的语法。
-
@hitzg 不工作我的意思是“按下键”消息没有出现,这意味着没有发生任何事件或没有收到信号。
-
@BasJansen,它适用于我的机器。我已经从这个页面复制代码并用 python 3.4.3 编译它
-
@saldenisov 请在问题中提及它适用于 python 3,因为提供的代码不能在 python 2.7 上运行。
标签: python python-3.x matplotlib pyqt5