-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmytableview.h
71 lines (52 loc) · 1.94 KB
/
mytableview.h
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifndef MYTABLEVIEW_H
#define MYTABLEVIEW_H
#include <QTableView>
#include <QDropEvent>
class MyTableView: public QTableView {
Q_OBJECT
int m_dropRow;
public:
MyTableView(QWidget *parent)
: QTableView(parent), m_dropRow(0)
{
setSelectionMode(QAbstractItemView::SingleSelection);
setSelectionBehavior(QAbstractItemView::SelectRows);
setDragEnabled(true);
setAcceptDrops(true);
setDragDropMode(QAbstractItemView::DragDrop);
setDefaultDropAction(Qt::MoveAction);
setDragDropOverwriteMode(false);
setDropIndicatorShown(true);
}
Q_INVOKABLE int selectedRow() const
{
QItemSelectionModel *selection = selectionModel();
return selection->hasSelection() ? selection->selectedRows().front().row() : -1;
}
void reset()
{
QTableView::reset();
QObject::connect(model(), &QAbstractTableModel::rowsInserted, this, [this](const QModelIndex &parent, int first, int last) {
Q_UNUSED(parent)
Q_UNUSED(last)
m_dropRow = first;
});
}
void dropEvent(QDropEvent *e)
{
if (e->source() != this || e->dropAction() != Qt::MoveAction)
return;
int dragRow = selectedRow();
QTableView::dropEvent(e); // m_dropRow is set by inserted row
if (m_dropRow > dragRow)
--m_dropRow;
// The following code would take care of selecting the dropped row after the event.
// It works on Linux and Windows, but not on macOS for some reason.
// In the make it is not queue and has the same effect as selectRow(m_dropRow),
// which changes the selection and causes the drop to happen in the wrong place.
// QMetaObject::invokeMethod(this,
// std::bind(&MyTableView::selectRow, this, m_dropRow),
// Qt::QueuedConnection); // Postpones selection
}
};
#endif // MYTABLEVIEW_H