-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsaveable_widget.h
123 lines (108 loc) · 3.3 KB
/
saveable_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#ifndef SAVABLE_WIDGET_H
#define SAVABLE_WIDGET_H
#include <QObject>
#include <QWidget>
#include <QPointer>
#include <map>
#include <atomic>
#include <QSettings>
#include <utility>
namespace utility
{
template<class T>
class SaveableWidget
{
private:
//we should use plain pointer as key, but it may be deleted, thats why hold QPointer to do real access
struct value_t
{
QPointer<QWidget> ptr;
QByteArray value;
};
std::map<QWidget*, value_t> lastSett;
const QString prefix;
static inline std::atomic<bool>& getResetter()
{
static std::atomic<bool> need_reset(false);
return need_reset;
}
protected:
SaveableWidget() = default;
SaveableWidget(QString prefix):
lastSett(),
prefix(std::move(prefix))
{
}
QString getSettingsGroupName(QWidget* widget) const
{
return prefix + widget->objectName();
}
void readSettings(QWidget* window)
{
if (window)
{
lastSett[window] = value_t{window, window->saveGeometry()};
if (!getResetter())
{
QSettings settings;
settings.beginGroup(getSettingsGroupName(window));
QVariant value = settings.value("geometry");
if (!value.isNull())
window->restoreGeometry(value.toByteArray());
else
{
//supporting old saves
value = settings.value("pos");
if (!value.isNull())
{
window->move(settings.value("pos").toPoint());
window->resize(settings.value("size").toSize());
}
}
recurseRead(settings, window);
settings.endGroup();
}
getResetter() = false;
}
}
void writeSettings(QWidget* window)
{
if (window)
{
QSettings settings;
settings.beginGroup(getSettingsGroupName(window));
settings.setValue("pos", window->pos());
settings.setValue("size", window->size());
settings.setValue("geometry", window->saveGeometry());
recurseWrite(settings, window);
settings.endGroup();
settings.sync();
}
}
virtual void recurseRead(QSettings& settings, QObject* object)
{
Q_UNUSED(settings)
Q_UNUSED(object)
}
virtual void recurseWrite(QSettings& settings, QObject* object)
{
Q_UNUSED(settings)
Q_UNUSED(object)
}
virtual ~SaveableWidget() = default;
public:
void resetSizePos()
{
for (const auto& p : lastSett)
{
if (p.second.ptr)
p.second.ptr->restoreGeometry(p.second.value);
}
}
static void resetUIOnRead()
{
getResetter() = true;
}
};
}
#endif // SAVABLE_WIDGET_H