0

I'm adding some checkBoxes recursively in tableWidget cells (always in column 1) on a specific function. The final nummber of those checkboxes is not defined and depends on the user input.

QStringList matID;
for(int i=0; i<matID.size(); i++
{
   ui->tableWidget->insertRow( ui->tableWidget->rowCount() );

   QCheckBox *checkBox = new QCheckBox();
   ui->tableWidget->setItem(ui->tableWidget->rowCount()-1,0,checkBox)
}

I would like to connect each one of them with a signal-slot connection which tells me which one has been checked.

Can anyone help me? I don't really understand how to do it...

thanks Giuseppe

piepolitb
  • 31
  • 4
  • 1
    Simply add in your for-loop: `connect(checkBox, &QCheckBox::stateChanged, [=](int state){ qDebug() << "Checkbox clicked" << state; });` – user3606329 Oct 18 '17 at 14:55
  • thank you, but like you said I can't say which one has been checked: I always get 2 or 0 whichever checkbox is clicked – piepolitb Oct 19 '17 at 06:33
  • I better explain myself: I would like to emit a signal which gives me the value of i (the row number where the clicked checkbox is) – piepolitb Oct 19 '17 at 07:03
  • You call getCurrentRow, but that may fail because you insert a QCheckBox. So you need to make a workaround https://stackoverflow.com/questions/46641743/qt-table-widget-button-to-delete-row/46643069 – user3606329 Oct 19 '17 at 10:59

1 Answers1

1

There are four solutions for this problem. I'll only describe the cleanest possiblity.

The best solution is to actually to make your item checkable. You can do this by setting the Qt::ItemIsUserCheckable flag on the item using setFlags(), remember to also keep the defaults.

QStringList matID;
for(int i=0; i<matID.size(); i++
{
   ui->tableWidget->insertRow( ui->tableWidget->rowCount() );

   QTableWidgetItem *item = ui->tableWidget->getItem(ui->tableWidget->rowCount()-1,0);
   item->setFlags(item->getFlags() | Qt::ItemIsUserCheckable);
}

Then, as explained in Qt/C++: Signal for when a QListWidgetItem is checked? (ItemWidgets are similar enough), you can then listen on itemChanged and check using checkState().

The other methods would be:

  • set an delegate for your column

  • create a QSignalMapper to map your own QCheckBox pointers to some value identifying your rows

  • Use the QObject::sender() member function to figure out which checkbox was responsible, and resolve it back to the row on your own.

Daniël Sonck
  • 869
  • 7
  • 9