QTreeWidget如何关闭选择功能

4

默认情况下,QTreeWidget会管理行的选择(当您单击一行时,它会将其突出显示,当您单击另一行时,它会突出显示并取消先前的行),但我不想要这个功能,并且无法找到关闭它的方法。

2个回答

8

您可以使用QAbstractItemView类的setSelectionMode(这是从QTreeWidget继承而来的)来设置组件的无选择模式。像这样做(抱歉,代码是C++):

yourtreeView->setSelectionMode(QAbstractItemView::NoSelection);

在这种情况下,项目不会被选中,但您仍然会看到它们周围的焦点矩形。要解决此问题,您可以通过调用以下方法将小部件设置为不接受焦点:
yourtreeView->setFocusPolicy(Qt::NoFocus);

如果您的树部件需要接受焦点,但不应该绘制焦点矩形,则可以使用自定义项代理,并在绘制之前从项的状态中删除State_HasFocus状态。类似于这样:

class NoFocusDelegate : public QStyledItemDelegate
{
protected:
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
};

void NoFocusDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
{
    QStyleOptionViewItem itemOption(option);
    if (itemOption.state & QStyle::State_HasFocus)
        itemOption.state = itemOption.state ^ QStyle::State_HasFocus;
    QStyledItemDelegate::paint(painter, itemOption, index);
}

....

NoFocusDelegate* delegate = new NoFocusDelegate();
yourtreeView->setItemDelegate(delegate);

1
非常感谢,我在 setSelectionModel() 中迷失了方向,没想到在 QAbstractItemView 中找到了答案,感谢 Serge。 - spearfire
感谢您和提问者,pyqt版本为:yourtreeView.setSelectionMode(QAbstractItemView.NoSelection) yourtreeView.setFocusPolicy(QtCore.Qt.NoFocus) - 无名小路

3
感谢上面的回答,我认为Python版本是 (^ ^):最初的回答。
yourtreeView.setSelectionMode(QAbstractItemView.NoSelection)
yourtreeView.setFocusPolicy(QtCore.Qt.NoFocus)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接