将导航工具栏添加到图中(matplotlib和PyQt4)

时间:2015-05-23 13:48:22

标签: python python-2.7 user-interface matplotlib pyqt4

我想在我的PyQt4 GUI中创建一个导航工具栏,但我无法使其工作,我必须承认我大部分都是复制粘贴此代码而我并不是真的得到它。如果您能告诉我如何添加NavigationToolbar并解释它是如何制作的,那将会很棒。先感谢您。

顺便说一下。我见过This Post,但我认为它与我的不同,我无法弄清楚如何使用它。

from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):

    def __init__( self ):
        self.fig = Figure()
        self.ax = self.fig.add_subplot( 111 )

        FigureCanvas.__init__( self, self.fig )
        FigureCanvas.setSizePolicy( self, QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding )
        FigureCanvas.updateGeometry( self )


class matplotlibWidget(QtGui.QWidget):

    def __init__( self, parent = None ):
        QtGui.QWidget.__init__( self, parent )
        self.canvas = MplCanvas()
        #self.toolbar = self.canvas.toolbar #Dunno How :(

        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget( self.canvas )
        self.setLayout( self.vbl )

1 个答案:

答案 0 :(得分:3)

我设法解决了这个问题,代码看起来应该是这样的

from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):

    def __init__( self ):
        self.fig = Figure()
        self.ax = self.fig.add_subplot( 111 )

        FigureCanvas.__init__( self, self.fig )
        FigureCanvas.setSizePolicy( self, QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding )
        FigureCanvas.updateGeometry( self )


class matplotlibWidget(QtGui.QWidget):

    def __init__( self, parent = None ):
        QtGui.QWidget.__init__( self, parent )
        self.canvas = MplCanvas() #create canvas that will hold our plot
        self.navi_toolbar = NavigationToolbar(self.canvas, self) #createa navigation toolbar for our plot canvas

        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget( self.canvas )
        self.vbl.addWidget(self.navi_toolbar)
        self.setLayout( self.vbl )