2

I am trying to add a NavigationToolbar to my tool. I managed to embed it in a widget but only the "Save the figure" option (highlighted in green) works. The zoom and the edit options (in red) are disabled. I don't understand why some functionalities don't work while the save option works. Thank you.

My code so far:

class Ui_MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.btn_map_country.clicked.connect(self.map_country)
        self.graph2 = MyCanvas()
        self.gridLayout_3.addWidget(self.graph2, 0, 2, 1, 1)

    def map_country(self):
        self.graph2.figure.clf()
        self.axes = self.graph2.figure.add_subplot(111)

        map = Basemap(projection='cyl',lon_0=0,resolution='l')
        map.readshapefile('shape_test', 'state')

        countries = ['Australia', 'Canada', 'France', 'Russia']
        patches   = []
        patches2   = []

        for info, shape in zip(map.state_info, map.state):
            if info['ADMIN'] in countries:
                patches.append( Polygon(np.array(shape), True) )
            else:
                patches2.append( Polygon(np.array(shape), True) )

        self.axes.add_collection(PatchCollection(patches, facecolor= '#81F781', edgecolor='k', linewidths=0.5, zorder=2))
        self.axes.add_collection(PatchCollection(patches2, facecolor= '#DAD3D1', edgecolor='k', linewidths=0.5, zorder=2))

        map.drawmapboundary(fill_color='#A9D0F5')
        self.graph2.draw()

class MyCanvas(FigureCanvas):
    def __init__(self, *args, **kwargs):
        self.figure = plt.figure()
        FigureCanvas.__init__(self, self.figure)
        self.figure.patch.set_facecolor("None")
        self.canvas = FigureCanvas(self.figure)
        toolbar = NavigationToolbar(self.canvas, self)

Here the result: enter image description here

1 Answer 1

3

You are not saving a reference to the toolbar, so I'm guessing it is being garbage collected.

Change the toolbar instantiation line to:

self.toolbar = NavigationToolbar(self.canvas, self)

EDIT: Consider following the pattern of this stack overflow answer (explicitly add the toolbar and canvas to a Qt layout, etc).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.