我有一个包含整数排序列表的模型。模型的新条目如下所示:
if (!causesCollision(iCode))
{
beginInsertRows(QModelIndex(), this->rowCount(), this->rowCount());
this->_codes.append(iCode);
qSort(this->_codes);
endInsertRows();
return true;
}
我需要使用此模型的QListView自动突出显示模型的新条目,但目前我无法找到新创建的行的索引。 this-> _codes是QList< int>。
首先,我尝试了rowsInserted(...)信号,但它只报告最后添加了一行,而不是列表中添加新项目的位置。
我尝试过这样的事情:
int iRow = this->_codes.indexOf(iCode);
QModelIndex index = this->index(iRow, 0);
emit ModelChanged(index);
将ModelChanged(索引)信号连接到QListView的setCurrentIndex(索引)插槽,但它不起作用。
答案 0 :(得分:0)
如果this->_codes
是一个列表,您可以轻松获取排序后插入的项目的索引。我会按以下方式重写您的插入代码:
if (!causesCollision(iCode))
{
// Calculate the insertion position in the list.
int row = 0;
while (row < _codes.size() && _codes.at(row) < iCode) {
row++;
}
beginInsertRows(QModelIndex(), row, row + 1);
_codes.insert(row, iCode); // Always insert sorted.
endInsertRows();
return true;
}
此后rowsInserted()
信号将指示插入新行的正确位置。