【问题标题】:Selecting a row in QTreeView programmatically以编程方式在 QTreeView 中选择一行
【发布时间】:2011-02-11 09:57:42
【问题描述】:

我有一个以 QFileSystemModel 作为模型的 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 是什么?
  • 我假设selectionQItemSelectionModel
  • @ssc 我猜selectiontreeview-&gt;selectionModel()

标签: c++ qt qt4 qtreeview


【解决方案1】:

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

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

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

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

【讨论】:

  • 您也可以使用QItemSelectionModel::ClearAndSelect 代替QItemSelectionModel::Select 在选择之前自动清除选择。
  • 由于QItemSelectionModel::Rows 的简单性,这个答案要好得多。编辑答案以包含评论的建议。
【解决方案2】:

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

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

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

treeview->setSelectionBehavior (QAbstractItemView::SelectRows)

【讨论】:

  • 尝试您的解决方案。 PS。已经设置了 SelectRows 行为(如第二行问题所述)
猜你喜欢
  • 1970-01-01
  • 2017-03-29
  • 2011-09-10
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多