【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);
    }
}
相关推荐
踩着两条虫7 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB7 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
即使再小的船也能远航7 小时前
【Python】安装
开发语言·python
Irissgwe7 小时前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃8 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
萌新小码农‍8 小时前
python装饰器
开发语言·前端·python
KK溜了溜了8 小时前
Python从入门到精通
服务器·开发语言·python
故事和你919 小时前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论
threelab9 小时前
Three.js 初中数学函数可视化 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
xiaoshuaishuai89 小时前
C# CDN加速与离线包优化PowerSetting慢问题
开发语言·windows·spring·c#