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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4967660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:02:36  来源:igfitidea点击:

Selecting a row in QTreeView programmatically

c++qtqt4qtreeview

提问by the JinX

I have a QTreeView with QFileSystemModel as model.

我有一个 QTreeView 与 QFileSystemModel 作为模型。

The QTreeView has SelectionBehavior set to SelectRows.

QTreeView 将 SelectionBehavior 设置为 SelectRows。

In my code I read a dataset to select and then select them via:

在我的代码中,我读取了一个要选择的数据集,然后通过以下方式选择它们:

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

This selects a cell, not the row . .

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

Have added a stupid workaround, but would rather fix this the correct way.

添加了一个愚蠢的解决方法,但宁愿以正确的方式解决这个问题。

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

Or is that ^^ the only way to do it?

或者这是 ^^ 唯一的方法吗?

采纳答案by Elmar de Koning

You can also select an entire row using an QItemSelection:

您还可以使用 QItemSelection 选择整行:

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

Also if you also want row selection for user clicks you need to set the selection behavior:

此外,如果您还需要为用户点击选择行,则需要设置选择行为:

treeview->setSelectionBehavior (QAbstractItemView::SelectRows)

回答by alex

If you want to select a full row, you should use the following:

如果要选择整行,则应使用以下内容:

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

Note that you may sometimes first want to clear the selection:

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

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