Rachael
Rachael

Reputation: 1995

Dynamically & sequentially naming & instantiating widgets qt

I'm creating a new instance of QTableWidgetItem for each row the user may add, and adding it to a QVector of QTableWidgetItems.

I'd like to do soemthing like the following to name each instance in the following iteration with the row number included in the instance name:

 QVector<QCheckBox> *checkBox_array;

  for(int r=0;r<user_input;r++)
  {
      ui->tableWidget->insertRow(r);        
      *checkBox%1.arg(r) = new QCheckBox;   //create an instance "checkBox1" here
      checkBox_array->pushBack(checkBox%1.arg(r))            
  }

or something like the following, which does not compile in its current state:

 for(int r=0;r<7;r++)
{
  ui->tableWidget->insertRow(r);


  checkBox_array->push_back();
  checkBox_array[r] = new QCheckBox;
  ui->tableWidget->setCellWidget(r,2,checkBox_array[r]);

}

is this possible? How can I work around this issue? All I need is to get the new widgets into the array without having to name them explicitly. Thanks in advance!

Thanks in advance.

Upvotes: 0

Views: 580

Answers (1)

Jablonski
Jablonski

Reputation: 18514

Try something like this:

for(int r=0;r<7;r++)
{
 ui->tableWidget->insertRow(r);
 ui->tableWidget->setCellWidget(r,2,new QCheckBox(QString("checkBox%1").arg(r)));
}

It creates some widgets.

When you want change something in this widget or get data then use cellWidget() method, but don't forget cast it! For example:

for(int r=0;r<7;r++)
{
 QCheckBox* curBox = qobject_cast<QCheckBox*>(ui->tableWidget->cellWidget(r,2));
 if(curBox)
 {
    qDebug() << curBox->text() << curBox->isChecked();
    curBox->setText("This is new Text");
 }
 else
     qDebug() << "fail";
}

Upvotes: 3

Related Questions