tableview.cc 1.79 KB
Newer Older
1
2
3
#include "radixwidgets/tableview.hh"

#include <QApplication>
4
#include <QClipboard>
5
#include <QHeaderView>
6
7
#include <QKeyEvent>

8
namespace radix {
9

10
11
TableView::TableView(QWidget *parent)
    : QTableView(parent) {}
12

13
14
15
void TableView::copy() {
  // selected items
  auto selected = selectionModel()->selectedIndexes();
16

17
18
19
20
  // selection is empty
  if (selected.empty()) {
    return;
  }
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  // data cells, unique rows, unique columns
  QHash<int, QHash<int, QString>> cells;
  QList<int> rows;
  QList<int> cols;

  // process selected indices
  {
    // row/column sets
    QSet<int> rs;
    QSet<int> cs;

    // determine min/max row/columns
    for (const auto &index : selected) {
      rs << index.row();
      cs << index.column();
      cells[index.row()][index.column()] = index.data().toString();
38
39
    }

40
41
    rows = rs.toList();
    cols = cs.toList();
42

43
44
45
    qSort(rows);
    qSort(cols);
  }
46

47
48
49
  // row/column header models
  auto rhmodel = verticalHeader()->model();
  auto chmodel = horizontalHeader()->model();
50

51
52
  // table data
  QString data;
53

54
55
56
57
58
  // add column headers
  for (auto col : cols) {
    data.append('\t').append(
        chmodel->headerData(col, Qt::Horizontal).toString());
  }
59

60
61
62
63
  // add cell data
  for (auto row : rows) {
    // add row header
    data.append('\n').append(rhmodel->headerData(row, Qt::Vertical).toString());
64

65
66
67
68
69
70
71
72
73
74
75
    // add row's cells
    for (auto col : cols) {
      data.append('\t');

      // row's data
      auto &rd = cells[row];

      // current cell is valid
      if (rd.contains(col)) {
        data.append(rd[col]);
      }
76
    }
77
78
79
80
81
82
83
84
85
86
87
88
  }

  // store in clipboard
  QApplication::clipboard()->setText(data);
}

void TableView::keyPressEvent(QKeyEvent *event) {
  if (event->matches(QKeySequence::Copy)) {
    copy();
  } else {
    QTableView::keyPressEvent(event);
  }
89
}
90
}  // namespace radix