【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);
    }
}
相关推荐
半夏知半秋14 分钟前
mongodb的复制集整理
服务器·开发语言·数据库·后端·学习·mongodb
一点七加一26 分钟前
Harmony鸿蒙开发0基础入门到精通Day09--JavaScript篇
开发语言·javascript·ecmascript
nvd1128 分钟前
python异步编程 -协程的实际意义
开发语言·python
沐知全栈开发2 小时前
NumPy 统计函数
开发语言
青光键主2 小时前
C语言内功强化之const修饰指针
c语言·开发语言
骷大人3 小时前
php安装skywalking_agent
开发语言·php·skywalking
恋恋西风3 小时前
Qt 打开文件列表选择文件,实现拖拽方式打开文件,拖拽加载
开发语言·qt
闲人编程3 小时前
使用Python进行量化交易入门
开发语言·python·统计分析·lambda·量化·codecapsule
奔跑吧 android3 小时前
【Qt】【1. 版本特性介绍】
qt·cpp·qml