How to use ChartView at DockWidget



  • I tried adding ChartView to DockWidget but ChartView was not shown(only blank dockwidget was shown).
    The code is as follows.

    [mainwindow.cpp]
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        Chart *chart = new Chart;
        chart->setTitle("Chart");
        chart->legend()->hide();
        chart->setAnimationOptions(QChart::AllAnimations);
    
        QChartView chartView(chart);
        chartView.setRenderHint(QPainter::Antialiasing);
    
        QDockWidget *chartwidget = new QDockWidget();
        chartwidget->setWidget(&chartView);
        addDockWidget(Qt::LeftDockWidgetArea, chartwidget);
    
        ui->setupUi(this);
    }
    

    However, following code could show the chartview at dockwidget.

    [main.cpp]
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
    
        Chart *chart = new Chart;
        chart->setTitle("Chart");
        chart->legend()->hide();
        chart->setAnimationOptions(QChart::AllAnimations);
    
        QChartView chartView(chart);
        chartView.setRenderHint(QPainter::Antialiasing);
    
        QDockWidget *chartwidget = new QDockWidget();
        chartwidget->setWidget(&chartView);
        w.addDockWidget(Qt::LeftDockWidgetArea, chartwidget);
    
        w.show();
    
        return a.exec();
    }
    

    Why is chartview not shown in the mainwindow.cpp?

    Thanks


  • Qt Champions 2016

    Hi and welcome
    You might have classic error where the object runs out of scope.

    QChartView chartView(chart); << not using new. so local variable
    chartwidget->setWidget(&chartView); << assign to other object
    } << here chartView is deleted. runs out of scope. when function ends.

    It did work in the "working" sample as return a.exec() prevented it from running out of scope
    as it stays in there until app ends.



  • @mrjj

    Thank you for your reply!!
    I did solve the problem.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.