PyQt5 QML内的MatPlotlib

2024-04-25 08:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须在我的项目中使用MatPlotlib。然而,我需要在PyQt5中设计QML应用程序,据我所知,matplotlib绘图是小部件。所以,我需要在QML中使用matplotlib图

我的问题是,有没有办法在QML中显示交互式matplotlib绘图?(所谓交互,我指的不仅仅是一个已保存为图像的图形,理想情况下是使用标准工具栏进行缩放等。)

here中,它以前问过,但没有回答。有人能帮我吗


Tags: 项目图像应用程序图形绘图标准matplotlib部件
1条回答
网友
1楼 · 发布于 2024-04-25 08:48:54

如果您可以使用小部件,那么它与PyQT4没有太大区别。这个答案是greatly inspired by this thread

PyQT5兼容代码:

import sys, random

from PyQt5.QtWidgets import (
    QMainWindow,
    QApplication,
    QWidget,
    QVBoxLayout,
    QPushButton,
    QHBoxLayout,
)

import matplotlib
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure


class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # The main_frame keeps all widgets on itself
        self.main_frame = QWidget()

        # Create the interactive matplotlib  figure
        self.fig = Figure((10.0, 16.0), dpi=100)

        # Create figure canvas that gets a reference to self.fig
        # in its __init__
        self.canvas = FigureCanvas(self.fig)
        self.ax = self.fig.add_subplot(111)

        # Create the matplotlib navigation toolbar
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # VBox (V for vertical) where the canvas is placed above the toolbar
        plotVbox = QVBoxLayout()
        plotVbox.addWidget(self.canvas)
        plotVbox.addWidget(self.mpl_toolbar)

        # Another VBox with a button, could eventually hold more
        # vertically ordered buttons
        controls = QVBoxLayout()
        self.button = QPushButton("Refresh")
        self.button.clicked.connect(self.refresh)
        controls.addWidget(self.button)

        # HBox (h for horizontal) where the
        # controls VBox with buttons is on the left
        # and the VBox with the plot is on the riht
        hbox = QHBoxLayout()
        hbox.addLayout(controls)
        hbox.addLayout(plotVbox)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)

    def refresh(self):
        """
        Here, the functionality of the 'Refresh' button is implemented.
        Note that we do not return anything, instead we modify the state 
        of the AppForm instance.
        """
        self.ax.clear()
        x = [random.random() for i in range(10)]
        y = [random.random() for i in range(10)]
        self.ax.plot(x, y, "o")
        self.canvas.draw()


def main():
    """
    Open the main window.
    """
    app = QApplication(sys.argv)
    form = AppForm()
    form.show()
    app.exec_()


if __name__ == "__main__":
    main()

相关问题 更多 >