以编程方式在QTreeView中选择一行

问题描述:

我有一个以QFileSystemModel为模型的QTreeView。以编程方式在QTreeView中选择一行

QTreeView将SelectionBehavior设置为SelectRows。

在我的代码我看了一个数据集来选择,然后通过选择它们:

idx = treeview->model()->index(search); 
selection->select(idx, QItemSelectionModel::Select); 

这将选择单元格,而不是一行。 。

已经添加了一个愚蠢的解决方法,但宁愿修复这个正确的方法。

for (int col=0; col< treeview->model()->columnCount(); col++) 
{ 
    idx = treeview->model()->index(search, col); 
    selection->select(idx, QItemSelectionModel::Select); 
} 

或者是^^唯一的办法吗?

selection->select (
    QItemSelection (
     treeview->model()->index (search, 0), 
     treeview->model()->index (search, treeview->model()->columnCount() - 1)), 
    QItemSelectionModel::Select); 

此外,如果你也想行选择为用户点击您需要设置选择行为:

treeview->setSelectionBehavior (QAbstractItemView::SelectRows) 
+4

什么是“选择”? – ssc 2014-11-10 09:10:54

+1

我假设`selection`是[QItemSelectionModel](http://doc.qt.io/qt-5/qitemselectionmodel.html)。 – altendky 2016-08-11 12:21:27

您也可以使用QItemSelection选择整行要选择一整行,您应该使用以下内容:

selection->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); 

请注意,你有时可能首先想要清除选择:

selection->select(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); 
+0

尝试您的解决方案。 PS:已经设置了SelectRows行为(如第二行问题所述) – 2011-02-11 10:57:12

如果你想