2017-09-27 96 views
0

我用qt Creator创建了一个UI,在这个UI中只有一个按钮和一个小部件(我们分别称之为button和char_container); 我需要在chart_container内以编程方式添加chartview。 我没有更改默认布局。QT在其他小部件中插入小部件

我尝试下面的代码,但它不工作:

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(仅设置父级是不够的,AFAIK)。 – dbrank0

回答

4

最好的方式来添加窗口小部件内的另一个方法是使用一个布局,因为我在下面:

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

我需要添加此行,因为QT Creator不会自动添加布局,所以我得到了一个sigsegv异常QGridLayout * gridLayout = new QGridLayout; ui-> chart_container-> setLayout(gridLayout); –

+0

我已经解决了它,点击按钮后,我刚刚添加了一个布局到chart_container,然后我得到了一个sigsegv对ui-> chart_container-> layout() –

+0

返回的指针@AntonioDelSannio它基本上是我的建议,只有你在Qt Designer的帮助下做到了。如果有帮助,请将我的答案标记为正确。 – eyllanesc