尝试从插槽更改 QTableWidgetItem 的前台时出现分段错误

Segmentation fault when trying to change foreground at QTableWidgetItem from a slot

提问人:shevy 提问时间:7/20/2023 最后编辑:shevy 更新时间:7/20/2023 访问量:62

问:

当我尝试动态创建表及其项目时出现错误。根据 QComboBox 项的状态,我正在更改 Qt:DisplayRole 项的背景颜色。行数是随机的,可能会有所不同。错误仅在行的特定索引之后发生。就像有 15 排一样,它可能会或不会在第 5 排、第 6 排或第 14 排崩溃。它总是一个随机数,我不明白为什么。我知道该错误可能与项目的错误索引有关。但是当我调试我的应用程序时,qDebug()索引总是正确的

下面是我的代码的一个略微简化的示例:

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)
   }
}

我试图捕获一个错误,它只发生在setForeground()的最后一部分。我试探它适用于表中的所有项目。但它只适用于其中的几个。当我尝试更改项目的 QFlags 时,此错误也会重复出现。我还尝试手动指向项目的现有索引,但应用程序也因分段错误而崩溃。ChatGPT 也没有帮助我:)

C++ Qt Segmentation-Fault qtablewidget qt-signals

评论

0赞 Aconcagua 7/20/2023
你似乎简化得太多了——定义导致 int 不再有效......Column
0赞 Jeremy Friesner 7/20/2023
您可能希望在取消引用这些指针之前添加代码来检查这些指针的返回值,因为这些方法中的任何一个都可能返回 .例如:tableList.at(someIndexOfExistingTable)item(currentRow, 0)NULLQTableWidget * t = tableList.at(someIndexOfExistingTable); QTableWidgetItem * i = t ? t->item(currentRow, 0) : NULL; if (i) i->setForeground((stateIndex==off)?Qt::Gray:Qt::Black);
0赞 shevy 7/20/2023
谢谢你的回答。我尝试检查 NULL 并且项目始终存在。

答: 暂无答案