如何在Qt Creator MainWindow中的特定容器中创建对象?

时间:2011-06-17 17:43:19

标签: c++ qt

希望这个问题很简单。我需要在GUI的特定区域中在运行时生成几个按钮。我想要创建的对象是复选框。以下是创建这些复选框的代码部分:

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 * 20, j * 20, 20, 20);
        }
    }
}

我的问题是如何理解这个想法,但是在我想要的特定区域创建这些复选框?该区域称为dim1,它是QTabWidget的小部件。

编辑:更新了代码

2 个答案:

答案 0 :(得分:2)

Troubadour基本上是正确的,你需要将正确的小部件设置为父级。虽然QScrollArea默认没有小部件,但你需要像这样创建它:

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

重要的是你使用checkBoxArea->setWidgetResizable(true),否则你每次调整大小时都必须手动设置大小。

如果窗口小部件没有显示在您期望的位置,那么大部分时间都有以下原因之一:

  • 错误的父母
  • 不可见:使用show()
  • 零大小:使用setGeoemetry

答案 1 :(得分:0)

您不希望将MainWindow的复选框作为父级,因为它们的位置将相对于该小部件。相反,您希望将它们添加到QCsrollArea的小部件,即

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

我假设你在QScrollArea上设置了一个小部件?如果没有,那么只需使用普通QWidget

checkBoxArea->setWidget( new QWidget() );