在 QtDesigner GUI 中嵌入 matplotlib 图

Jul*_*ell 5 python qt matplotlib pyqt5

我试图通过在使用 Qt 设计器创建的 Qt GUI 中嵌入一个 matplotlib 图形来混淆我的方式。我已经能够通过 Python 创建我想要的图形。我已经创建了一个带有小部件的基本 GUI,以允许我选择/加载输入文件,并在嵌入在 GUI 中的 matplotlib 图形中绘制这些文件中的数据。我通过向名为 的 GUI 添加一个空白小部件来完成此操作plotwidget,然后GraphInit使用此小部件作为输入调用该类。

我目前面临的问题是,虽然我的绘图在 GUI 中显示并根据需要进行更新,但它似乎没有注意在我的 Python 代码(创建 FigureCanvas 的位置)或为它定义的大小策略plotWidgetQt Designer 中的小部件。我一直在使用这个演示作为这个项目的起点。但是,所有这些示例都完全从 Python 中生成了 GUI。我怀疑我在将 matplotlib 图形分配给小部件时做错了什么,但我无法弄清楚是什么。

代码(删除了导入和绘图代码,但添加图形的核心在那里):

import sys
import os
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QMessageBox, QFileDialog, QPushButton, QLabel, QRadioButton, QDoubleSpinBox, QSpinBox, QWidget, QSizePolicy, QMainWindow
import PyQt5.uic

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

import json
from datetime import datetime
import numpy as np


class LogViewer(QApplication):
    def __init__(self):
        QApplication.__init__(self, sys.argv)
        self.ui = UI()

    @staticmethod
    def main():
        vwr = LogViewer()
        vwr.run()

    def run(self):
        self.ui.win.show()  # Show the UI
        self.ui.run()  # Execute the UI run script
        self.exec_()


class Graph_init(FigureCanvas):

    def __init__(self, parent=None):

        fig = Figure()
        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()
        self.axes.grid()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class UI(object):
    def __init__(self):
        ui_path = os.path.dirname(os.path.realpath(__file__))
        self.win = PyQt5.uic.loadUi(ui_path + '\\logview.ui')
        self.filename = ui_path + '\\test.txt'
        self.plotWin = Graph_init(self.win.plotWidget)

    def run(self):
        self.init_ui()  # get initial values from the controllers
        self.attach_ui_connections()

    def init_ui(self):
        w = self.win
        w.txtLogFilename.setText(self.filename.split('/')[-1])  # just the file (no path)

    def attach_ui_connections(self):
        w = self.win



if __name__ == '__main__':
    LogViewer.main()
Run Code Online (Sandbox Code Playgroud)

GUI在此处可用。任何建议表示赞赏!

p-a*_*l-o 4

我检查了你的 ui 文件,plotWidget根本没有布局。尝试给它一个,我建议采用网格布局。

然后,在对画布进行父级设置之后

self.setParent(parent)
Run Code Online (Sandbox Code Playgroud)

尝试将其添加到父布局中:

parent.layout().addWidget(self)
Run Code Online (Sandbox Code Playgroud)