QT在一个小部件中插入另一个小部件

4
我用qt Creator创建了一个UI界面,在这个界面上只有一个按钮和一个小部件(我们分别称之为按钮和char_container); 我需要在char_container中通过编程方式添加一个图表视图。 我没有改变默认布局。
我尝试了下面的代码,但它不起作用:
void MainWindow::button_slot(){
    QtCharts::QChart *chart = new QtCharts::QChart();
    QtCharts::QChartView *chartView = new QtCharts::QChartView(chart);
    chartView->setParent(ui->chart_container);
    this.repaint();
}

1
您仍然需要将您的ChartView添加到MainWindow中(仅设置父对象是不够的,据我所知)。 - dbrank0
1个回答

10

将小部件添加到另一个小部件内的最佳方法是使用布局,如下所示:

//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);
}

我需要添加这些代码行,因为QT Creator不会自动添加布局,所以我得到了一个sigsegv异常。 QGridLayout *gridLayout = new QGridLayout; ui->chart_container->setLayout(gridLayout); - Antonio Del Sannio
我已经解决了,在点击按钮后,我只是向chart_container添加了一个布局,在此之前,我得到了ui->chart_container->layout()返回的指针上的sigsegv。 - Antonio Del Sannio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接