PyQt5 QML内部的MatPlotlib

问题描述 投票:0回答:1

我必须在我的项目中使用MatPlotlib。但是,我需要在PyQt5中设计QML应用程序,据我了解,matplotlib图是Widget。因此,我需要在QML中使用matplotlib图。

我的问题是,有没有一种方法可以在QML中显示交互式matplotlib图? (通过交互式,我的意思是不仅是保存为图像的图形,最好是使用标准的缩放工具栏等。)

here中,它曾问过,但没有得到回答。有人可以帮我吗?

python matplotlib pyqt qml pyqt5
1个回答
0
投票

如果您可以使用小部件,则与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()
© www.soinside.com 2019 - 2024. All rights reserved.