No figure options in matplotlib NavigationToolbar2QT actions

Viewed 1028

I'm using PyQt5 and matplotlib to make GUI for making plots. I wanted to add more functionality when I press the toolbar buttons. For example when I want to do something when I click on the home button I do:

self.toolbar._actions['home'].triggered.connect(self.do_something)

and it works. However, I cannot find the action for the figure options button shown below in orange: matplotlib toolbar

when I do:

self.toolbar._actions

It returns

{'home': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE4C8>, 'back': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE558>, 'forward': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE5E8>, 'pan': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE708>, 'zoom': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE798>, 'configure_subplots': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE828>, 'save_figure': <PyQt5.QtWidgets.QAction object at 0x0000020D91ECE9D8>}

dictionary containing only 7 objects without the Figure Options/edit axis button.

How can I do something after the figure options button is clicked?

1 Answers

That QAction is not directly accessible but if you analyze the source code you see that it has "Customize" as text so you can use findChildren to get it:

for action in self.toolbar.findChildren(QtWidgets.QAction):
    if action.text() == "Customize":
        action.triggered.connect(self.do_something)
        break

Another option is to override the edit_parameters() method since it is called by that QAction:

import sys
import numpy as np

from PyQt5 import QtCore, QtWidgets

from matplotlib.backends.backend_qt5agg import (
    FigureCanvas,
    NavigationToolbar2QT,
)
from matplotlib.figure import Figure


class NavigationToolbar(NavigationToolbar2QT):
    def edit_parameters(self):
        print("before")
        super(NavigationToolbar, self).edit_parameters()
        print("after")


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)

        self.m_canvas = FigureCanvas(Figure(figsize=(5, 3)))
        self.m_toolbar = NavigationToolbar(self.m_canvas, self)
        layout.addWidget(self.m_canvas)
        self.addToolBar(self.m_toolbar)

        self._static_ax = self.m_canvas.figure.subplots()
        t = np.linspace(0, 10, 501)
        self._static_ax.plot(t, np.tan(t), ".")


if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()
Related