【发布时间】:2015-10-26 08:53:27
【问题描述】:
我想在 Qt4 小部件中显示 Line2D 实例。但是当我运行代码时,它只是显示一个空白图。
这是我的代码。
import sys
from PyQt4 import QtGui
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.lines import Line2D
class Qt4MplCanvas(FigureCanvas):
"""Class to represent the FigureCanvas widget"""
def __init__(self, parent):
# plot definition
self.fig = Figure()
self.axes = self.fig.add_subplot(111)
x = [1,1]
y=[2,2]
self.line = Line2D(x, y, marker = 'o', markerfacecolor = 'r', animated = True)
self.axes.add_line(self.line)
self.axes.set_xlim((0,3))
self.axes.set_ylim((0,3))
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# set the parent widget
self.setParent(parent)
# we define the widget as expandable
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
# notify the system of updated policy
FigureCanvas.updateGeometry(self)
class ApplicationWindow(QtGui.QMainWindow):
"""Example main window"""
def __init__(self):
# initialization of Qt MainWindow widget
QtGui.QMainWindow.__init__(self)
# set window title
self.setWindowTitle("Matplotlib Figure in a Qt4 Window With NavigationToolbar")
# instantiate a widget, it will be the main one
self.main_widget = QtGui.QWidget(self)
# create a vertical box layout widget
vbl = QtGui.QVBoxLayout(self.main_widget)
# instantiate our Matplotlib canvas widget
qmc = Qt4MplCanvas(self.main_widget)
# instantiate the navigation toolbar
vbl.addWidget(qmc)
# set the focus on the main widget
self.main_widget.setFocus()
# set the central widget of MainWindow to main_widget
self.setCentralWidget(self.main_widget)
# create the GUI application
qApp = QtGui.QApplication(sys.argv)
# instantiate the ApplicationWindow widget
aw = ApplicationWindow()
# show the widget
aw.show()
# start the Qt main loop execution, exiting from this script
# with the same return code of Qt application
sys.exit(qApp.exec_())
我的代码中有两个类。 Qt4MplCanvas 类用于绘制 Line2D 图形。类 ApplicationWindow 是写一个窗口并在其上添加一个小部件。
【问题讨论】:
标签: python matplotlib qt4 pyqt4 data-visualization