【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);
    }
}
相关推荐
siy233316 分钟前
[c语言日记] 数组的一种死法和两种用法
c语言·开发语言·笔记·学习·链表
njxiejing34 分钟前
Python NumPy安装、导入与入门
开发语言·python·numpy
Rhys..1 小时前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
土了个豆子的1 小时前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
@菜菜_达1 小时前
Lodash方法总结
开发语言·前端·javascript
GISer_Jing2 小时前
低代码拖拽实现与bpmn-js详解
开发语言·javascript·低代码
@areok@2 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言2 小时前
【C++进阶】---- map和set的使用
开发语言·c++
Elnaij2 小时前
从C++开始的编程生活(8)——内部类、匿名对象、对象拷贝时的编译器优化和内存管理
开发语言·c++
yb0os13 小时前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc