3

Recently I found the way that checkbox places in the middle of QtableWidget item. However, I do not know how to check state whether or not button is clicked. Could you tell me how to check button state?

here is what Ive found code:

QWidget *pWidget = new QWidget();
QCheckBox *pCheckBox = new QCheckBox();
QHBoxLayout *pLayout = new QHBoxLayout(pWidget);
pCheckBox->setCheckState(Qt::Checked);
pLayout->addWidget(pCheckBox);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0,0,0,0);
pWidget->setLayout(pLayout);
ui->tableWidget2->setCellWidget(2,2, pWidget);
Jongju Kim
  • 184
  • 2
  • 13

2 Answers2

1

Although this is very late you can solve it like this:

auto field = ui->tableWidget2->cellWidget(2, 2, pWidget);

std::cout << qobject_cast<QCheckBox*>(field)->isChecked() << std::endl;

This works for other types as well (QComboBox etc.). Although it would probably be better to just use the checkbox functionality that QTableWidgetItem already has.

This example might not work if you are using a tristate checkbox in which case you should call: checkState() and compare it to Qt::CheckState. If qobject_cast<T> does not work out you can use a reinterpret_cast<T>.

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
0

I assume you created your checkboxes in the QWidgetTable like this:

int row...;int column...;
...
QTableWidgetItem *checkBoxItem = new QTableWidgetItem();
checkBoxItem->setCheckState(Qt::Unchecked);
ui->Table->setItem(row, column, checkBoxItem);

You can check the status of the item that corresponds to your widget in another function like this:

void MainWindow::on_Table_cellClicked(int row, int column)
{
    QTableWidgetItem *checkBoxState = ui->Table->item(row, column);

    if(ui->Table->item(row,column)->checkState())
    {
        checkBoxState->setCheckState(Qt::Unchecked);
        ui->Table->setItem(row, column, checkBoxState);
    }
    else
    {
        checkBoxState->setCheckState(Qt::Checked);
        ui->Table->setItem(row, column, checkBoxState);
    }
}
  • 1
    Wait, why are you creating a new `QTableWIdgetItem`? – rubenvb Dec 13 '18 at 15:53
  • change `QTableWidgetItem *checkBoxState = new QTableWidgetItem();` to `QTableWidgetItem *checkBoxState = ui->Table->item(row, column);` – eyllanesc Dec 13 '18 at 16:51
  • can you tell how can we check type of cell that its checkbox or text field etc – user889030 Dec 18 '19 at 06:33
  • I think you didn't know realize the special point of this question, the special point is using `setCellWidget` to set item instead of using `ui->Table->setItem` to set item , i didn't test it, but i guess in this way, `ui->Table->item(row, column)` will return something that you didn't expected. – Wade Wang Jul 01 '21 at 05:59