提问人:shevy 提问时间:7/20/2023 最后编辑:shevy 更新时间:7/20/2023 访问量:62
尝试从插槽更改 QTableWidgetItem 的前台时出现分段错误
Segmentation fault when trying to change foreground at QTableWidgetItem from a slot
问:
当我尝试动态创建表及其项目时出现错误。根据 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 也没有帮助我:)
答: 暂无答案
评论
Column
tableList.at(someIndexOfExistingTable)
item(currentRow, 0)
NULL
QTableWidget * t = tableList.at(someIndexOfExistingTable); QTableWidgetItem * i = t ? t->item(currentRow, 0) : NULL; if (i) i->setForeground((stateIndex==off)?Qt::Gray:Qt::Black);