pyqt5界面嵌入matplotlib
时间: 2023-05-28 18:01:15 浏览: 337
在PyQt5的界面中嵌入Matplotlib实际上非常简单。以下是代码示例,它将Matplotlib嵌入到一个PyQt5窗口应用程序中:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QHBoxLayout, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
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, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 & Matplotlib Demo")
self.setGeometry(100, 100, 800, 600)
# Create the button to update the plot
update_button = QPushButton("Update Plot", self)
update_button.resize(100, 25)
update_button.move(10, 10)
update_button.clicked.connect(self.update_plot)
# Create the canvas to display the plot
canvas = PlotCanvas(self, width=5, height=4)
canvas.move(0, 100)
# Create a layout for the window
layout = QVBoxLayout()
layout.addWidget(update_button)
layout.addWidget(canvas)
# Create a central widget and set the layout
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.update_plot()
def update_plot(self):
# Clear the figure
self.canvas.axes.clear()
# Create some data to plot
x = [1, 2, 3, 4, 5]
y = [3, 5, 1, 7, 9]
# Plot the data
self.canvas.axes.plot(x, y)
# Update the canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这段代码首先定义了一个名为PlotCanvas的类,它是一个受Matplotlib支持的Qt小部件,并用于在Matplotlib图形上绘制。接下来,MainWindow类继承自QMainWindow并定义了一个PyQt5应用程序的主窗口。在构造函数中,我们创建了一个用于更新绘图的按钮,以及一个用于在其中绘制Matplotlib图形的PlotCanvas对象。然后,我们将两个控件添加到窗口布局中并显示窗口。最后,在update_plot方法中,我们定义了要绘制的数据以及绘图命令,然后将其呈现到Matplotlib图形上并更新窗口。
阅读全文