在QtDesigner GUI中嵌入matplotlib图

时间:2018-01-04 16:20:21

标签: python qt matplotlib pyqt5

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

我目前面临的问题是,当我的绘图在GUI中显示和更新时,它似乎没有注意我的Python代码(其中创建了FigureCanvas)中为其定义的大小策略)或Qt Designer中的plotWidget小部件。我一直在使用this demo等作为这个项目的起点。但是,所有这些示例都完全从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()

GUI可用here。任何建议表示赞赏!

1 个答案:

答案 0 :(得分:2)

我查看了您的ui文件,plotWidget根本没有布局。试着给它一个,我建议一个网格布局。

然后,在为画布做父母之后

self.setParent(parent)

尝试将其添加到父版面:

parent.layout().addWidget(self)
相关问题