Home > Mobile >  mpl_connect key_press_event event does not fire in Scrollable Window on Python Matplotlib
mpl_connect key_press_event event does not fire in Scrollable Window on Python Matplotlib

Time:12-03

I have multiple plot inside scrollable window QT5 widget as below.

class ScrollableWindow(QtWidgets.QMainWindow):
    def __init__(self, fig):
        self.qapp = QtWidgets.QApplication([])

        QtWidgets.QMainWindow.__init__(self)
        self.widget = QtWidgets.QWidget()
        self.setCentralWidget(self.widget)
        self.widget.setLayout(QtWidgets.QVBoxLayout())
        self.widget.layout().setContentsMargins(0,0,0,0)
        self.widget.layout().setSpacing(0)

        self.fig = fig
        self.canvas = FigureCanvas(self.fig)
        self.canvas.draw()
        self.scroll = QtWidgets.QScrollArea(self.widget)
        self.scroll.setWidget(self.canvas)

        self.nav = NavigationToolbar(self.canvas, self.widget)
        self.widget.layout().addWidget(self.nav)
        self.widget.layout().addWidget(self.scroll)

        self.show()
        exit(self.qapp.exec_()) 

I try to capture key press event with mpl_connect.

def key_selector(event):
    print('Key pressed.')

fig, axes = plt.subplots(ncols=4, nrows=5, figsize=(16,16))
for ax in axes.flatten():
    ax.plot([2,3,5,1])

fig.canvas.mpl_connect('key_press_event', key_selector)
a = ScrollableWindow(fig)

But mpl_connect 'key_press_event' does not fire. I try another e.g. 'button_press_event' and work as usual. Any advice or guidance on this would be greatly appreciated, Thanks.

CodePudding user response:

Have a look at this matplotlib issue. Basically, you need to activate the focus of Qt onto your matplotlib canvas.

    self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
    self.canvas.setFocus()
  • Related