在PyQt5设计的GUI界面中显示读取文件matplotlib绘制的图形
时间: 2024-05-12 07:20:18 浏览: 122
要在PyQt5设计的GUI界面中显示读取文件matplotlib绘制的图形,可以采用以下步骤:
1. 导入必要的库
```
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
```
2. 创建一个绘图函数,以便将读取的数据绘制成图形
```
def plot_data(data):
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot(data)
return fig
```
3. 在主窗口中创建一个QWidget,将绘图控件添加到其中,并设置布局
```
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('My Application')
self.setGeometry(100, 100, 800, 600)
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
layout = QVBoxLayout(central_widget)
canvas = FigureCanvas(plot_data(data))
layout.addWidget(canvas)
```
4. 运行程序,即可在GUI界面中显示读取文件matplotlib绘制的图形。
完整代码如下:
```
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
def plot_data(data):
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot(data)
return fig
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('My Application')
self.setGeometry(100, 100, 800, 600)
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
layout = QVBoxLayout(central_widget)
canvas = FigureCanvas(plot_data(data))
layout.addWidget(canvas)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
阅读全文