Rob Luca
Rob Luca

Reputation: 193

Getting QTableWidgetItem out of cellWidget()'s QCheckBox

I'm storing QCheckBox in QTableWidget, in following way:

QCheckBox *checkBox = new QCheckBox();
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout(widget);
layout->addWidget(checkBox);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0,0,0,0);
widget->setLayout(layout);
tableWidget->setCellWidget(row, 2, widget);

Then, I catch stateChanged() of the checkBox:

connect( checkBox, SIGNAL(stateChanged(int)), this, SLOT(checkBoxStateChanged(int)) );
void MainWindow::checkBoxStateChanged(int)
{
    QCheckBox * box = qobject_cast< QCheckBox * >( sender() );
    if( !box ) {
        return;
    }
}

Now, I can get to QTableWidget – it is box->parent()->parent()->parent(). Object before that, i.e. box->parent()->parent(), is qt_scrollarea_viewport (that's objectName()). I've searched children of the "viewport", and there's 16 QWidgets – the number of rows in my table. However, their children are only QHBoxLayout and QCheckBox. There apparently is no reference to QTableWidgetItem – it looks like if I were in some parallel object hierarchy, and QTableWidgetItem is in other hierarchy. Is that true? How to get the item?

Upvotes: 0

Views: 713

Answers (1)

Frodon
Frodon

Reputation: 3785

See this question: How to work with signals from QTableWidget cell with cellWidget set

Adapted to you case:

void MainWindow::checkBoxStateChanged(int)
{
    QCheckBox * box = qobject_cast< QCheckBox * >( sender() );
    if (box)
    {
        int row = box->property("row").toInt();
        int column = box->property("column").toInt();
        QTableWidgetItem* item = tableWidget->item(row, column);
    }
}

Upvotes: 1

Related Questions