如何在Pyside2 Qmainwindow gui内正确清除matplotlib图形?

时间:2019-09-05 07:16:26

标签: python user-interface pyside2

我正在Pyside2 QmainWindow小部件内绘制matplotlib图。但是,在完成绘制第一个图形之后,我关闭了QMainWindow小部件并尝试绘制其他图形,旧图形仍保留在画布上。调整窗口大小后,它只会刷新并显示新图。 (例如,单击窗口边缘并调整大小)

我已经尝试过fig.clf(),plt.close(fig),fig.clear(),但是这些仅解决了阻止新图覆盖旧图的问题。

import matplotlib.pyplot as plt
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from engine.core.graph.draw_graph_matching import draw
import os


class GraphMatchingWindow(QMainWindow, QObject):
    started = Signal(str)
    feedback = Signal(str)
    finished = Signal(str)
    closed = Signal(str)

def __init__(self, input_topology_base=None, input_topology_realtime=None, annotated_graph_file=None,
             annotated_graph_tmp=None):
    super().__init__()
    self._main = QWidget()
    self.setCentralWidget(self._main)
    self.input_topology_base = input_topology_base
    self.input_topology_realtime = input_topology_realtime
    self.annotated_graph_file = annotated_graph_file
    self.annotated_graph_tmp = annotated_graph_tmp
    self.count = 0

    layout = QVBoxLayout(self._main)

    self.fig = plt.figure()
    static_canvas = FigureCanvas(self.fig)
    layout.addWidget(static_canvas)
    self.addToolBar(NavigationToolbar(static_canvas, self))

def set(self, input_topology_base, input_topology_realtime, annotated_graph_file, annotated_graph_tmp):
    self.input_topology_base = input_topology_base
    self.input_topology_realtime = input_topology_realtime
    self.annotated_graph_file = annotated_graph_file
    self.annotated_graph_tmp = annotated_graph_tmp

def show(self):
    draw(self.fig, self.input_topology_base, self.input_topology_realtime, self.annotated_graph_file)
    super().show()
    self.finished.emit("Graph Matching displayed in popup window.\n")

def close_all(self):
# i have tried all sorts of clear but to no avail
    self.fig.clear()
    plt.close(self.fig)
    # self.fig.clf()   # clear figure
    self.close_tmp()

def close_tmp(self):
    if self.annotated_graph_tmp:
        os.close(self.annotated_graph_tmp)
        os.remove(self.annotated_graph_file)

def closeEvent(self, event):
    self.closed.emit("Graph Matching window closed.\n")
    self.close_all()

当我关闭窗口时,close_all函数触发。

0 个答案:

没有答案