Qt How to check state checkbox in QtableWidget

6.8k views Asked by At

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

There are 2 answers

4
Ferhat Özdogan On

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);
    }
}
0
Floris Velleman On

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>.