4

I've created an UI with qt Creator,in this UI there is just a button and a widget (let's call it respectively button and char_container); I need to add a chartview programmatically inside the chart_container. I didn't change the default layout.

I've tried the following code,but it does not work:

void MainWindow::button_slot(){
    QtCharts::QChart *chart = new QtCharts::QChart();
    QtCharts::QChartView *chartView = new QtCharts::QChartView(chart);
    chartView->setParent(ui->chart_container);
    this.repaint();
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    You still need to add your chartview to MainWindow (just setting parent is not enough, AFAIK). – dbrank0 Sep 27 '17 at 11:13

1 Answers1

10

The best way to add a widget inside another is to use a layout, as I show below:

//on constructor
ui->chart_container->setLayout(new QVBoxLayout);


void MainWindow::button_slot()
{
    QtCharts::QChart *chart = new QtCharts::QChart();
    QtCharts::QChartView *chartView = new QtCharts::QChartView(chart, ui->chart_container);
    ui->chart_container->layout()->addWidget(chartView);
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I needed to add this lines beacause QT Creator doesn't add a layout automatically,so i got a sigsegv exception QGridLayout *gridLayout = new QGridLayout; ui->chart_container->setLayout(gridLayout); – Antonio Del Sannio Sep 27 '17 at 13:09
  • I've solved it,after clicking on the button,i just added a layout to the chart_container,before i got a sigsegv on the pointer returned by ui->chart_container->layout() – Antonio Del Sannio Sep 27 '17 at 13:50