flashburn flashburn - 2 months ago 7
C++ Question

why gui is crashing when setting a value in the first column of tablewidget

I have

QTableWidget
in my UI. The first column is a set of
QRadioButton
s. Here is how it looks:
enter image description here

I've added the following code to the
MainWindow
constructor:

for (char i = 0; i < ui->currentSetting1TableWidget->rowCount(); i++)
ui->currentSetting1TableWidget->setCellWidget(i, 0, new QRadioButton(ui->currentSetting1TableWidget));


I've also added the following code:

void MainWindow::on_currentSetting1TableWidget_clicked(const QModelIndex &index)
{
QRadioButton *b = (QRadioButton *)ui->currentSetting1TableWidget->cellWidget(index.row(), 1);
b->setChecked(true);
}


My code is crashing when it executes
b->setChecked(true);
. I assume it has something to do with me not properly understanding what casting in
C++
and what exactly is returned by
cellWidget
in
Qt
. I tried to investigate it but I can't see what the problem is. I would really appreciate any help on this.

Answer

Use qobject_cast/dynamic_cast for casting types derived from QObject and check the returned value.

You seem to be setting cell widget in column 0, but you're accessing it from column 1. It may very well return nullptr right away, from looking at your screenshot.

Comments