[英]How to get QModelIndex to insert a new row in a QAbstractTableModel?
[英]Finding QModelIndex of new entry into Model
我有一個模型,其中包含一個排序的整數列表。 該模型的新條目如下所示:
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(index)信號連接到QListView的setCurrentIndex(index)插槽,但是它不起作用。
如果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()
信號將指示新行已插入的正確位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.