写pyqt代码显示matplotlib图片
时间: 2023-02-09 12:59:42 浏览: 135
这是一个简单的例子,显示如何使用 PyQt 和 Matplotlib 在 GUI 中显示图像。
```
import sys
from PyQt5 import QtWidgets, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.title = 'Matplotlib in PyQt'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.m = PlotCanvas(self, width=5, height=4)
self.m.move(0,0)
self.show()
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = x ** 2
self.axes.plot(x, y, 'r')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
这个例子中,我们创建了一个名为App的主窗口,然后在这个主窗口中添加了一个画布,用于显示 Matplotlib 图像。我们还定义了一个名为PlotCanvas的类,该类继承自FigureCanvas,并在其中绘制了一个简单的曲线图.
阅读全文