QListView与QStandardItemModel不显示通过代码
选择高亮我有一个QListView
填入QStandardItemModel
或QStringListModel
(基于内容的简单性...列数)。QListView与QStandardItemModel不显示通过代码
在加载或切换小工具时,我搜索应该选择的项目,并尝试突出显示它。
if (first)
{
m_myListView.setModel(m_standardItemModel);
QList<QStandardItem*> lst = m_standardItemModel->findItems(m_value1, Qt::MatchExactly, 1);
if(!lst.isEmpty())
{
QModelIndex index = lst.at(0)->index();
qDebug() << index.row(); // tells me correct row
//m_myListView.setCurrentIndex(index); // no change if I use
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
m_myListView.scrollTo(index);
}
}
else
{
m_myListView.setModel(m_stringListModel);
int i = m_stringListModel->stringList().indexOf(m_value2);
if (i >= 0)
{
QModelIndex index = m_stringListModel->index(i);
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
m_myListView.scrollTo(index);
}
}
m_stringListModel
版本正确突出显示(并滚动到项目)。 m_standardItemModel
版本不突出显示行,并且不滚动到项目。但在随后的使用,它提供了正确的数据,选择指数:
QModelIndexList indexList = m_myListView.selectionModel()->selectedIndexes();
if (!indexList.isEmpty())
{
QModelIndex index = indexList.first();
if (index.isValid())
{
row = index.row();
data1 = m_standardItemModel->index(row, 1).data().toString();
...
所以......看来,选择工作,但如果这样做,为什么我看不到一个亮点? (和scrollTo()
)
注 - 代码非常庞大,但我验证了重新加载模型的可能性,并可能丢失选择 - 此外,QStringListModel
版本正常工作。
这是QStandardItemModel
的典型行为,还是有我必须做的事情,比如设置BackgroundRole
类型的数据?
如何突出显示应用QStandardItemModel
的列表视图的选择?
因为发现该项目比显示项目的不同,列表视图是无法选择它...
2解决方案:要么创建从一个发现了一个不同的QModelIndex
,指着显示栏,或选择一个包含所需索引的整行:
m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
我看到你的代码,可能你想选择你的模型的第一个元素?让我们尝试:
void MyClass::selectFirstElement() {
const QModelIndex firsIndex = _myModel->index(0,0);
if (index.isValid())
ui->listView->setCurrentIndex(firstIndex);
ui->listView->scrollTo(firstIndex);
}
}
你能分享m_standardItemModel实施?同时正确配置清单:
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->listView->setSelectionBehavior(QAbstractItemView::SelectRows); // Or Columns
检查您QStandarItem有选择flag启用。有关更多信息,请参阅http://doc.qt.io/qt-4.8/qt.html#ItemFlag-enum。
最后,你可以确保&列从模型直接获取指标在同一行中,像这样的索引存储在正确的模式:
QModelIndex index = lst.at(0)->index();
index = _model->index(index.row(), index.column());
对不起,我英文不好:S