Qt中关于QTableWidget成员函数selectedItems和itemAt(QPoint)无法获取无数据Item的处理方式

问题描述

QTableWidget控件,有item,但是item没有数据,界面表现上可以选中,但是selectedItems函数返回的结果中,没有无数据但被选中的item。itemAt函数也是,给定的坐标点,有item,但是item没有数据,返回结果是空指针。

问题原因分析

代码中并没有主动向QTableWidget中添加数据,数据添加全靠界面上双击编辑自动添加的。QTableWidget的界面上显示有单元格,但有单元格不一定有item。由于我们没有在代码中主动添加数据,也就没有item。而直接在界面双击单元格进行编辑时,QTableWidget会自动调用setItem函数向QTableWidget添加item,没有数据的单元格自然也就没有item,而没有item,selectedItems和itemAt都不会有结果返回。

问题解决方案

主动添加item

在QTableWidget设置好单元格后,不管是否要添加数据,先主动调用setItem函数为点单元格设置item。

使用QModelIndex

该方法也是Qt官方推荐的方法,不依赖于单元格是否有数据。将selectedItems和itemAt替换成selectionModel和indexAt,具体代码如下

cpp 复制代码
void Dialog::deleteSelect()
{
    QItemSelectionModel *selectionModel = ui->tableWidget->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedRows(0);
    
    for(auto it = selectedIndexes.rbegin(); it != selectedIndexes.rend(); ++it)
        ui->tableWidget->removeRow(it->row());
}

bool Dialog::eventFilter(QObject *object, QEvent *event)
{
    if(object == ui->tableWidget->viewport())
    {
        if(event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
            if(mouseEvent)
            {
                QPoint pos = mouseEvent->pos();
                QModelIndex index = ui->tableWidget->indexAt(pos);
                if(!index.isValid())
                {
                    ui->tableWidget->clearSelection();
                }
            }
        }
    }

    return QDialog::eventFilter(object, event);
}
相关推荐
zimoyin2 分钟前
浅浅了解下0拷贝技术
java·linux·开发语言
AI架构师易筋6 分钟前
AIOps 告警归因中的提示工程:从能用到可上生产(4 阶梯)
开发语言·人工智能·llm·aiops·rag
你的冰西瓜13 分钟前
C++中的array容器详解
开发语言·c++·stl
随丶芯29 分钟前
IDEA安装leetcode-editor插件
java·开发语言
Ccjf酷儿43 分钟前
C++语言程序设计 (郑莉)第六章 数组、指针和字符串
开发语言·c++
禹曦a1 小时前
Java实战:Spring Boot 构建电商订单管理系统RESTful API
java·开发语言·spring boot·后端·restful
superman超哥1 小时前
精确大小迭代器(ExactSizeIterator):Rust性能优化的隐藏利器
开发语言·后端·rust·编程语言·rust性能优化·精确大小迭代器
芒克芒克1 小时前
虚拟机类加载机制
java·开发语言·jvm
陌路201 小时前
C++28 STL容器--array
开发语言·c++
FPGAI1 小时前
Python之函数
开发语言·python