要在PyQt5的分组框中显示Matplotlib图表,你需要使用Matplotlib的FigureCanvasQTAgg
类将图表嵌入到PyQt5的窗口中。以下是一个简单的示例,展示了如何在PyQt5的分组框中嵌入Matplotlib图表:
以下是一个简单的例子,展示了如何在PyQt5的分组框中显示一个简单的折线图:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGroupBox, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 with Matplotlib'
self.left = 100
self.top = 100
self.width = 640
self.height = 400
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# 创建分组框
groupBox = QGroupBox('Matplotlib Chart')
layout = QVBoxLayout(groupBox)
# 创建Matplotlib图表
fig = Figure()
ax = fig.add_subplot(111)
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
ax.plot(t, s)
# 创建FigureCanvas对象
canvas = FigureCanvas(fig)
layout.addWidget(canvas)
# 设置主窗口的中心部件
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
canvas.draw()
方法来刷新图表。numpy
库,因为上面的示例代码中使用了numpy
来生成数据。通过上述步骤,你应该能够在PyQt5的分组框中成功显示Matplotlib图表。如果需要进一步的定制或者功能扩展,可以参考Matplotlib和PyQt5的官方文档。
领取专属 10元无门槛券
手把手带您无忧上云