I have an error when i try to dynamically create a table and it's items. And based on a state of QComboBox item I'm changing the background colour of Qt:DisplayRole item. The number of rows is random and could vary. Error occurs only after particular index of a row. Like when there is a 15 rows, it could or couldn't crash at 5th, 6th or maybe 14th row. It is always a random number and i can't understand why. And i understand that error could be related to a wrongly pointed index of an item. But when i was debugging my app qDebug() indexes were always correct
Here is a slightly simplified example of my code:
QList<QTableWidget *> tableList; //Global variable;
QList<QComboBox *> comboBoxList; //Global variable;
int rowCount = 5;
int columnCount = 2;
tableList.append(new QTableWidget());
tableList.last()->setRowCount(rowCount);
tableList.last()->setColumnCount(columnCount);
for (int row = 0; row < tableList.last()->rowCount(); row++)
{
tableList.last()->setItem(row, 0, new QTableWidgetItem());
// This is the problematic item that causes segmentation fault \/
tableList.last()->item(row, 0)->setData(Qt::DisplayRole, QVariant(1));
QComboBox *tmpComboBox = new QComboBox();
// My stupid temporary workaround with row indexes that also could cause troubles, but overall it works
tmpComboBox->setObjectName(QString::number(row));
comboBoxList.append(tmpComboBox);
comboBoxList.last()->addItem("on", "on");
comboBoxList.last()->addItem("off", "off");
tableList.last()->setItem(row, 1, comboBoxList.last())
connect(comboBoxList->last(), SIGNAL(currentIndexChanged(int)), this, SLOT(onStateChanged(int)));
}
// Slot realisation
void Widget::onStateChanged(int stateIndex)
{
const int on = 0;
const int off = 1;
// My stupid temporary workaround with row indexies that also could cause troubles, but overall it works
int currentRow = sender()->objectName().toInt();
if(stateIndex == off)
{
//This is the place of crash
tableList.at(someIndexOfExistingTable)->item(currentRow, 0)->setForeground(Qt::Gray)
}
else
{
//Also the place
tableList.at(someIndexOfExistingTable)->item(currentRow, 0)->setForeground(Qt::Black)
}
}
I tried to catch an error and it only occurs on the last section of setForeground(). I expceted it to work with all items of the table. But it works only with a few of them. This error also repeats itself when i try to change QFlags of an item. I also tried to manually point an existing index of item but app also crashed with SEGMENTATION FAULT. ChatGPT didn't helped me either :)