开发者

How do I create objects in a specific container in my Qt Creator MainWindow?

Hopefully this question is an easy one. I need to generate a few buttons at run-time in a specific area of my GUI. The objects I want to create are checkboxes. Here is the part of the code that creates these checkboxes:

void MainWindow::on_generateBoxes_clicked()
{
    int x_dim = ui->xDim->value();
    int y_dim = ui->yDim->value();
    int z_dim = ui->zDim->value();
    QVector<QCheckBox*> checkBoxVector;
    for(int i = 0; i < x_dim; ++i){
        for(int j = 0; j < y_dim; ++j){
            checkBoxVector.append(new QCheckBox( ui->dim1 ));
            checkBoxVector.last()->setGeometry(i * 2开发者_高级运维0, j * 20, 20, 20);
        }
    }
}

My question is how do I take this idea, but create these checkboxes in the specific area I want? The area is called dim1, and it is a widget of a QTabWidget.

EDIT: Updated the code


Troubadour is basically right, that you need to set the right widget as parent. Though QScrollArea has by default no widget, you need to create it like this:

checkBoxArea = new QScrollArea(this); // this is the MainWindow or other parent
background = new QWidget;
checkBoxArea->setGeometry(0, 0, 200, 200);
checkBoxArea->setWidgetResizable(true); 
checkBoxArea->setWidget(background);
background->show();
for(int i = 0; i < 5; ++i){
    for(int j = 0; j < 5; ++j){
        checkBoxVector.append(new QCheckBox(background));
        checkBoxVector.last()->setGeometry(i * 20, j * 20, 20, 20);
    }
}

important is that you use checkBoxArea->setWidgetResizable(true) otherwise you would have to set the size manually each time you resize.

If a widget doesn't show up where you expect it to, this most of the time has one of those reasons:

  • wrong parent
  • invisible: use show()
  • zero size: use setGeoemetry


You don't want to parent the checkboxes to the MainWindow as then their positions will be relative to that widget. Instead you want to parent them to the widget of the QCsrollArea i.e.

checkBoxVector.append(new QCheckBox(checkBoxArea->widget()));

I assume you have set a widget on the QScrollArea? If not then just use a plain QWidget i.e.

checkBoxArea->setWidget( new QWidget() );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜