blob: bbde13e653007fe0bf9d97d644557a5469547b77 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include "copyeventfilter.h"
#include <QClipboard>
#include <QGuiApplication>
#include <QKeyEvent>
CopyEventFilter::CopyEventFilter(QAbstractItemView* view, int role) :
CopyEventFilter(view, [=](auto& index) { return index.data(role).toString(); })
{
}
CopyEventFilter::CopyEventFilter(
QAbstractItemView* view, std::function<QString(const QModelIndex&)> format) :
QObject(view), m_view(view), m_format(format)
{
}
bool CopyEventFilter::copySelection() const
{
if (!m_view->selectionModel()->hasSelection()) {
return true;
}
// sort to reflect the visual order
QModelIndexList selectedRows = m_view->selectionModel()->selectedRows();
std::sort(selectedRows.begin(), selectedRows.end(), [=](const auto& lidx, const auto& ridx) {
return m_view->visualRect(lidx).top() < m_view->visualRect(ridx).top();
});
QStringList rows;
for (auto& idx : selectedRows) {
rows.append(m_format(idx));
}
QGuiApplication::clipboard()->setText(rows.join("\n"));
return true;
}
bool CopyEventFilter::eventFilter(QObject* sender, QEvent* event)
{
if (sender == m_view && event->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->modifiers() == Qt::ControlModifier
&& keyEvent->key() == Qt::Key_C) {
return copySelection();
}
}
return QObject::eventFilter(sender, event);
}
|