目前已修复此问题!
我正在尝试使用带有嵌入式matplotlib画布的PyQt4制作GUI。当我将光标滚动到画布上时,我希望能够基于另外的按键控制行为(在这种情况下为控制)。但是,链接到'scroll_event'的mouseEvent的键属性始终为None。我测试了我的代码正确注册了'button_press_event'生成的mouseEvent的密钥。
在下面的示例中,on_press
方法正确打印了同时按下的键。而on_scoll
始终打印无。
如何访问鼠标滚动事件期间按下的键?
提前致谢!
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class GraphicTool(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.create_menu()
def on_press(self, event):
print event.key
def on_scroll(self, event):
print event.key
if event.key == 'ctrl':
# do something
pass
else:
# do something else
pass
def create_main_frame(self):
self.main_frame = QWidget()
# Create the mpl Figure and FigCanvas objects.
# 10x8 inches, 100 dots-per-inch
self.dpi = 100
self.fig = Figure((10.0, 8.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.axes = self.fig.add_subplot(111)
self.canvas.mpl_connect('scroll_event', self.on_scroll)
self.canvas.mpl_connect('button_press_event', self.on_press)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas,
self.main_frame)
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
self.main_frame.setLayout(vbox)
self.setCentralWidget(self.main_frame)
def main():
app = QApplication(sys.argv)
viewer = GraphicTool()
viewer.show()
viewer.raise_()
app.exec_()
if __name__ == "__main__":
main()
上面的简短示例实际上按预期工作。但是,当我将它合并到一个更大的项目中时,它就失败了。我将继续调试以查看是否有任何其他事件干扰滚动事件。
答案 0 :(得分:1)
我检查了你的代码。这是按预期工作的。
def on_scroll(self, event):
print event.xdata
print event.ydata
print event.key
if event.key == 'ctrl':
# do something
pass
else:
# do something else
pass
这是代码的输出。我刚刚在你的代码中添加了xdata和ydata。
0.480977867785
0.57896567718
control
0.480977867785
0.57896567718
shift
0.480977867785
0.57896567718
shift