【Qt】点击QTreeWidget空白处,使当前选择的Item失效

原因

有时在开发中,可能会对QTreeWidget进行操作,当点击feiQTreeWidgetItem时,需要焦点取消,无Item选中。

解决方案

可以通过设置事件过滤器进行实现。

1.QtreeWidget安装事件过滤器

cpp 复制代码
ui->treeWidget->viewport()->installEventFilter(this);

2.重写eventFliter()函数

如果光标不在Item上,就设置当前Item下标为空

cpp 复制代码
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(ui->treeWidget->viewport() == watched)
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *pME = (QMouseEvent*)event;
            if(pME->buttons() & Qt::LeftButton)
            {
                QModelIndex index = ui->treeWidget->indexAt(pME->pos());
                if(!index.isValid())
                {
                    ui->treeWidget->setCurrentIndex(QModelIndex());
                }
            }
        }
    }
    return QMainWindow::eventFilter(watched, event);
}

效果

选中状态

点击空白:

结论

用行动祈祷比用言语更能够使上帝了解

相关推荐
九转成圣9 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio9 小时前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
laowangpython9 小时前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫9 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch9 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI9 小时前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_0019 小时前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
念2349 小时前
f5 shape分析
开发语言·javascript·ecmascript
苍穹之跃9 小时前
某量JS逆向
开发语言·javascript·ecmascript
思茂信息9 小时前
CST软件如何进行参数化扫描?
运维·开发语言·javascript·windows·ecmascript·软件工程·软件需求