在PyQt GUI中嵌入FigureCanvas并使其填充整个图形,可以按照以下步骤进行操作:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
layout = QVBoxLayout()
layout.addWidget(self.canvas)
self.setLayout(layout)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Matplotlib in PyQt")
self.setGeometry(100, 100, 800, 600)
self.widget = MyWidget(self)
self.setCentralWidget(self.widget)
def plot_graph():
ax = widget.figure.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])
widget.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
plot_graph()
sys.exit(app.exec_())
这样,FigureCanvas就会被嵌入到PyQt GUI的小部件中,并填充整个图形。
关于FigureCanvas、matplotlib和PyQt的更多信息,可以参考以下链接:
领取专属 10元无门槛券
手把手带您无忧上云