试图在Qt QTreeView中选择一整行

Trying to select a full row in a Qt QTreeView

本文关键字:选择 QTreeView Qt      更新时间:2023-10-16

我正在尝试使用以下代码选择QTreeView组件中的完整行:

const QModelIndex topLeft = model->index(0, 0);
const QModelIndex bottomRight = model->index(model->rowCount(), model->columnCount());
ui->hidDescriptorView->selectionModel()->selection().select(topLeft, bottomRight);

我有点无能,一直在寻找周围使用const_cast等,试图让选择工作,但编译器给了我以下错误:

/.../mainwindow.cpp:93: error: member function 'select' not viable: 'this' argument has type 'const QItemSelection', but function is not marked const
            ui->hidDescriptorView->selectionModel()->selection().select(topLeft, bottomRight);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我来自之前的位,我设法做出一个选择,但只有一个单元格会被选中,所以我正在尝试上面的,以确保整个行被正确选择,就好像用户会点击它。

任何帮助将非常感激!

select()的签名为

const QItemSelection selection () const

。,您不能就地修改QItemSelection,因为它是一个const副本。作为一个副本,修改不会有任何影响。

相反,创建一个副本(或者只是创建一个新的QItemSelection)并通过select()传递它:
QItemSelection selection = view->selectionModel()->selection();
selection.select(topLeft, bottomRight);
view->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);

正如您所提到的,想要选择行,可能有更简单的方法:

view->selectionModel()->select(topLeft, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);

将用户的选择扩展为整行:

view->setSelectionBehavior(QAbstractItemView::SelectRows);

view.setCurrentIndex(