【Qt】QTableWidget设置可以选择多行多列,并能复制选择的内容到剪贴板

比如有一个 QTableWidget*m_tbwQuery

c++ 复制代码
m_tbwQuery->installEventFilter(this); //进行事件过滤处理

//设置可以选择多行多列
m_tbwQuery->setSelectionMode(QAbstractItemView::MultiSelection); 
m_tbwQuery->setSelectionBehavior(QAbstractItemView::SelectItems); 
m_tbwQuery->setFocusPolicy(Qt::StrongFocus);  // 或者 Qt::ClickFocus 或 Qt::TabFocus

//点击后,取消原来选择的
connect(m_tbwQuery, &QTableWidget::itemPressed, [=](QTableWidgetItem* item){
    if (item) {
        m_tbwQuery->clearSelection();
        m_tbwQuery->setSelectionMode(QAbstractItemView::MultiSelection);
        m_tbwQuery->setCurrentItem(item);
        item->setSelected(true);
    }
    });
    
// 双击选择一行
connect(m_tbwQuery, &QTableWidget::itemDoubleClicked, [=](QTableWidgetItem* item) {
    if (item) {
        m_tbwQuery->clearSelection();
        m_tbwQuery->setSelectionMode(QAbstractItemView::MultiSelection);
        m_tbwQuery->selectRow(item->row());
    }
    });

在事件过滤中处理键盘事件,快捷键是Ctrl+C

c++ 复制代码
/// 事件过滤
bool QueryDataTable::eventFilter(QObject* obj, QEvent* event) 
{
    if (obj == m_tbwQuery)
    {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->matches(QKeySequence::Copy)) {
                copySelectedCellsToClipboard();
                return true;  // Event handled
            }
        }
    }
    return QObject::eventFilter(obj, event);
}

最后是实现复制到剪贴板的函数

c++ 复制代码
// 复制选定单元格内容到剪贴板的函数
void QueryDataTable::copySelectedCellsToClipboard() 
{
    QItemSelectionModel* selectionModel = m_tbwQuery->selectionModel();
    QModelIndexList indexes = selectionModel->selectedIndexes();

    if (!indexes.isEmpty()) {
        qSort(indexes); // 为了确保数据按照视觉顺序排序
        QString text;
        QModelIndex previous = indexes.first();
        QModelIndex current;

        foreach(const QModelIndex & index, indexes) {
            if (index != previous) {
                if (index.row() != previous.row()) {
                    text += '\n';
                }
                else {
                    text += '\t';
                }
            }

            text += index.data(Qt::DisplayRole).toString();
            previous = index;
        }

        QApplication::clipboard()->setText(text);
    }
}
相关推荐
爱学习的小可爱卢12 分钟前
编程语言30年:从Java到Rust的进化史
java·开发语言·rust
一个很帅的帅哥14 分钟前
three.js和WebGL
开发语言·javascript·webgl
一 乐14 分钟前
校园社区系统|基于java+vue的校园悬赏任务平台系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吗~喽18 分钟前
【C++】模板进阶
c语言·开发语言·c++
毕设源码-钟学长21 分钟前
【开题答辩全过程】以 基于Python爬虫的二手房信息爬取及分析为例,包含答辩的问题和答案
开发语言·爬虫·python
layman052828 分钟前
在python中受限于GIL,进程中只允许一个线程处于允许状态,多线程无法充分利用CPU多核
开发语言·python
捧 花30 分钟前
Go Web 开发流程
开发语言·后端·golang·restful·web·分层设计
南猿北者31 分钟前
go语言基础语法
开发语言·后端·golang
CC.GG1 小时前
【Qt】Qt初识
开发语言·qt
好评1241 小时前
C/C++ 内存管理:摆脱野指针和内存泄漏
开发语言·c++·内存管理·c/c++