如何禁用QTableView的整列选择

How to disable whole column selection of QTableView?

本文关键字:列选 选择 何禁用 QTableView      更新时间:2023-10-16

void setSelectionBehavior(QAbstractItemView::SelectionBehBehavior behavior)

此函数接受三个值之一:用于选择项目、用于选择行和选择单元格。

问题:

我需要这样的情况,当单击一个单元格时,它被选中,当单击行索引时,行被选中,但当单击列标题时,整个列没有被选中。据我所知,使用此函数无法完成此操作。

我需要表视图的行为与设置SelectionBehavior::selectItems时完全相同。

但当用户单击标题时,不应选择该列。

我正在考虑禁用QHeaderView中的列选择,但找不到如何禁用?

来自我的应用程序:

    // get header from QTableView tableView (replace with your widget name)
    QHeaderView *header = new QHeaderView(Qt::Horizontal, tableView);
#if QT_VERSION < 0x50000
// Qt 4.8.1
    header->setResizeMode(QHeaderView::ResizeToContents);
#else
// Qt 5.2.0
    header->setSectionResizeMode(QHeaderView::ResizeToContents);
#endif
    header->setHighlightSections(false); // this is what you want

setHighlightSections(bool)插槽对Qt 4和Qt 5 有效

编辑:原谅你粗心大意!只有在将SelectRows或SelectItems与SingleSelection一起使用时,此选项才有效。您可以在源qheaderview.cppqtableview.cpp、槽voidQHeaderView::mousePressEvent(QMouseEvent *e);voidQTableViewPrivate::selectColumn(int column, bool anchor); 中找到证明

对于SelectItems可以使用此插槽:

    header->setClickable(false);