Matplotlib NavigationToolbar嵌入在Pyqt5中

时间:2018-05-24 00:08:30

标签: python-3.x matplotlib pyqt5

我正在尝试将NavigationToolbar添加到我的工具中。我设法将它嵌入到一个小部件中,但只有“保存图”选项(以绿色突出显示)才有效。缩放和编辑选项(红色)被禁用。我不明白为什么某些功能在保存选项有效时不起作用。谢谢。

到目前为止我的代码:

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)

结果如下: enter image description here

1 个答案:

答案 0 :(得分:1)

你没有保存对工具栏的引用,所以我猜它是垃圾收集。

将工具栏实例化行更改为:

[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class ServerRouteController : Controller {
    /// <summary>
    /// Load default index view
    /// </summary>
    /// <returns></returns>
    [Route("")]         //Match /ServerRoute
    [Route("[action]")] //Match /ServerRoute/Index
    public IActionResult Index() {
        return View();
    }
}

编辑:考虑遵循this堆栈溢出答案的模式(明确地将工具栏和画布添加到Qt布局等)。