QT在其他小部件中插入小部件

Ant*_*nio 2 c++ qt qwidget qt5 qchart

我用qt Creator创建了一个UI,在这个UI中只有一个按钮和一个小部件(让我们分别调用它按钮和char_container); 我需要在chart_container中以编程方式添加chartview.我没有更改默认布局.

我尝试了以下代码,但它不起作用:

void MainWindow::button_slot(){
    QtCharts::QChart *chart = new QtCharts::QChart();
    QtCharts::QChartView *chartView = new QtCharts::QChartView(chart);
    chartView->setParent(ui->chart_container);
    this.repaint();
}
Run Code Online (Sandbox Code Playgroud)

eyl*_*esc 7

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

//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);
}
Run Code Online (Sandbox Code Playgroud)