-
Notifications
You must be signed in to change notification settings - Fork 1
/
restorable_header_widget.h
67 lines (59 loc) · 2.33 KB
/
restorable_header_widget.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
#pragma once
#include <QAction>
#include <QHeaderView>
#include <QList>
#include <QWidget>
#include <QSettings>
template <class T>
class RestorableHeaderWidget : public T
{
public:
RestorableHeaderWidget(QWidget *parent) :
T(parent)
{
this->horizontalHeader()->setContextMenuPolicy(Qt::ActionsContextMenu);
this->horizontalHeader()->setSectionsMovable(true);
}
void saveHeaderSettings(QSettings &settings)
{
settings.setValue("HeaderState", this->horizontalHeader()->saveState());
settings.beginGroup("ColumnsWidths");
for (int col = 0; col<this->model()->columnCount(); col++) {
settings.setValue(QString::number(col), this->columnWidth(col));
}
settings.endGroup();
settings.beginGroup("ColumnsVisiblity");
for (int col = 0; col<this->model()->columnCount(); col++) {
settings.setValue(QString::number(col), this->isColumnHidden(col));
}
settings.endGroup();
}
void restoreHeaderSettings(QSettings &settings)
{
this->horizontalHeader()->restoreState(settings.value("HeaderState").toByteArray());
settings.beginGroup("ColumnsWidths");
for (int col = 0; col<this->model()->columnCount(); col++) {
int width = settings.value(QString::number(col), 0).toInt();
if (width)
this->setColumnWidth(col, width);
}
settings.endGroup();
settings.beginGroup("ColumnsVisiblity");
for (int col = 0; col<this->model()->columnCount(); col++) {
bool hidden = settings.value(QString::number(col), false).toBool();
this->setColumnHidden(col, hidden);
auto actionText = this->model()->headerData(col, Qt::Horizontal, Qt::ToolTipRole).toString();
if (actionText.isEmpty())
actionText = this->model()->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString();
auto *action = new QAction(actionText, this);
action->setCheckable(true);
action->setChecked(!hidden);
action->setData(col);
this->horizontalHeader()->addAction(action);
this->connect(action, &QAction::triggered, this, [=](bool checked) {
this->setColumnHidden(col, !checked);
});
}
settings.endGroup();
}
};