单击项目视图的空白区域时清除选择 [英] Clear selection when clicking on blank area of Item View

查看:60
本文介绍了单击项目视图的空白区域时清除选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 QTreeWidget 做了一个树结构,效果很好.但我有一个问题.通常,对于树结构,如果我想取消选择所有,我单击树小部件的空白区域.但是 QTreeWidget 似乎不支持(或者我不知道如何).

I made a tree structure with QTreeWidget, and it works well. But I have a problem with that. Commonly, with a tree structure, if I want to deselect all, I click on a blank area of the tree-widget. But QTreeWidget does not seem to support that (or I can't find out how).

子分类或其他方法可以解决问题吗?确定点击空白区域似乎是解决方案的关键,但我找不到信号或任何东西.

Could sub-classing or something else solve the problem? Determining a click on a blank area seems the key to the solution, but I can't find a signal or anything.

推荐答案

下面的示例代码将在单击空白区域或按下 Esc 时清除选择(和当前项目)树小部件具有键盘焦点.它适用于任何继承 QAbstractItemView(不仅仅是 QTreeWidget):

The example code below will clear the selection (and current item) when clicking on a blank area, or when pressing Esc when the tree widget has the keyboard focus. It will work with any widget which inherits QAbstractItemView (not just QTreeWidget):

class MyWidget(QTreeWidget):
    def keyPressEvent(self, event):
        if (event.key() == Qt.Key_Escape and
            event.modifiers() == Qt.NoModifier):
            self.selectionModel().clear()
        else:
            super(MyWidget, self).keyPressEvent(event)

    def mousePressEvent(self, event):
        if not self.indexAt(event.pos()).isValid():
            self.selectionModel().clear()
        super(MyWidget, self).mousePressEvent(event)

为了避免子类化,可以使用 事件过滤器相反:

To avoid subclassing, an event-filter can be used instead:

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.widget = QTreeWidget()
        self.widget.installEventFilter(self)
        self.widget.viewport().installEventFilter(self)
        ...

    def eventFilter(self, source, event):
        if ((source is self.widget and
             event.type() == QEvent.KeyPress and
             event.key() == Qt.Key_Escape and
             event.modifiers() == Qt.NoModifier) or
            (source is self.widget.viewport() and
             event.type() == QEvent.MouseButtonPress and
             not self.widget.indexAt(event.pos()).isValid())):
            self.widget.selectionModel().clear()
        return super(Window, self).eventFilter(source, event)

这篇关于单击项目视图的空白区域时清除选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆