我在模仿this simple graph embedding example。我成功地在我的GUI中嵌入了一个图形,当我按下按钮时它完美地工作。但问题是,当我第二次点击按钮时,它不会更新。它抛出以下错误
QLayout: Attempting to add QLayout "" to QWidget "centralwidget", which already has a layout
到目前为止,这是我的代码:
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100, stores = [], prices = []):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
self.prices = prices
self.stores = stores
self.compute_initial_figure()
FigureCanvas.__init__(self, fig)
self.setParent(parent)
self.setMinimumSize(400, 400)
self.setMaximumSize(800, 300)
def compute_initial_figure(self):
pass
class MyStaticMplCanvas(MyMplCanvas):
"""Simple canvas with a sine plot."""
def compute_initial_figure(self):
self.axes.clear() # To clear the axis every time and make new plot
y_pos = np.arange(4)
self.axes.bar(y_pos, self.prices)
self.axes.set_xticks(y_pos, minor=False)
self.axes.set_xticklabels(self.stores, fontdict=None, minor=False)
对于按钮,我有以下方法
def button_click(self):
.......
# Here is some logic that return prices and stores list which is used in self.sc
self.l = QtGui.QVBoxLayout(self.centralwidget)
self.sc = MyStaticMplCanvas(self.centralwidget, width=5, height=4, dpi=100, stores=stores, prices= prices)
self.l.addWidget(self.sc)
if (self.l.count() > 0): self.sc.deleteLater() # Added in new Edit but it also does not work
我尝试了很多选择:
1. self.sc.deleteLater() # It just removes the graph from GUI
2. self.sc.axes.clear() and self.sc.axes.cla() # Does nothing but returns above mentioned error
3. I deleted the layout from central widget and set it again but still nothing happened.
4. I tried this too --> `if (self.l.count() > 0): self.sc.deleteLater()` but it just delete the whole graph
我在哪里做错了?请指导。感谢