Close QChartView with main window?
Solved
General and Desktop
-
Hi, why doesnt a QChartView get closed if I close the mainwindow? Even when I put "cv.close" in the MainWindow destructor the chart window stays open...
mainwindow.h
class MainWindow : public QWidget { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: QPushButton *pushButtonDrawChart; QLineSeries *ls; QChart *chart; QChartView *cv; private slots: void drawChart(); };
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setGeometry(400,400,640,420); pushButtonDrawChart = new QPushButton("Draw Chart", this); connect(pushButtonDrawChart, &QPushButton::clicked, this, &MainWindow::drawChart); } MainWindow::~MainWindow() { qDebug() << "Destructor called"; } void MainWindow::drawChart(){ ls = new QLineSeries(); ls->append(0,1); ls->append(1,2); ls->append(2,3); ls->append(3,4); chart = new QChart(); chart->addSeries(ls); chart->createDefaultAxes(); cv = new QChartView(chart); cv->show(); }
-
- do not create a new chart and chartview every time you call drawChart, leave
chart = new QChart();
andcv = new QChartView(chart);
in the constructor. - call
chart->removeAllSeries()
indrawChart
before adding a new one - use
cv->show();
andcv->hide();
to togle the display of the chart - call
chart->deleteLater();
andcv->deleteLater();
in MainWindow's destructor - no need to make
ls
a member, a local variable is enough - put
pushButtonDrawChart
in a layout to ensure it's displayed correctly
- do not create a new chart and chartview every time you call drawChart, leave