如何在 QScrollArea 中动态添加和删除绘图小部件?

How to dynamically add and delete plot widgets in a QScrollArea?

我有一个带按钮的 GUI;我将一个新的 matplotlib 图添加到界面另一个选项卡的滚动区域。我可以多次这样做。问题是我想添加一个功能,其中“删除”按钮仅删除他所在的小部件。

这是我所拥有的最小可重现示例:

import sys

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

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

from matplotlib.figure import Figure


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

        # Window
        self.setWindowTitle("DataVisualizationPrototype")
        self.setGeometry(400, 200, 900, 800)
        self.activateWindow()
        self.raise_()

        self.tab_widget = TabWidget()
        self.setCentralWidget(self.tab_widget)


class TabWidget(QTabWidget):
    def __init__(self, parent=None):
        super(TabWidget, self).__init__(parent)

        self.tab1 = QWidget()
        self.plot_button = QPushButton("Add plot")
        lay = QVBoxLayout(self.tab1)
        lay.addWidget(self.plot_button)

        self.tab2 = QWidget()
        self.scroll_area = QScrollArea()
        self.scroll_container = QWidget()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.scroll_container)
        self.scroll_layout = QHBoxLayout(self.scroll_container)
        lay = QVBoxLayout(self.tab2)
        lay.addWidget(self.scroll_area)

        self.addTab(self.tab1, "Home")
        self.addTab(self.tab2, "Comparison")

        self.plot_button.clicked.connect(self.plot)

    def plot(self):
        canvas = FigureCanvas(Figure())
        ax = canvas.figure.add_subplot(111)
        toolbar = NavigationToolbar(canvas, self)
        dltbtn = QPushButton("Remove")

        container = QWidget()
        lay = QVBoxLayout(container)
        lay.addWidget(canvas)
        lay.addWidget(toolbar)
        lay.addWidget(dltbtn)

        self.scroll_layout.addWidget(container)
        container.setMinimumWidth(400)

        ax.plot([1, 2, 3, 4])
        ax.set_ylabel("some numbers")


def main():

    app = QApplication(sys.argv)
    view = MainWindow()
    view.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()

谁能帮忙写个命令删除删除按钮所在的'container'?

逻辑是消除小部件容器,因为如果它被消除,那么它的子容器也会被消除,为此,在发出点击信号时调用 deleteLater 方法就足够了。

dltbtn.clicked.connect(container.deleteLater)