Planned maintenance has been done but it did not solve the problem. So work will continue on this and a new time for trying updates will be announced asap.

Close QChartView with main window?



  • 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();	
    }
    

  • Qt Champions 2018

    • do not create a new chart and chartview every time you call drawChart, leave chart = new QChart(); and cv = new QChartView(chart); in the constructor.
    • call chart->removeAllSeries() in drawChart before adding a new one
    • use cv->show(); and cv->hide(); to togle the display of the chart
    • call chart->deleteLater(); and cv->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


  • Works, thank you.