1/* Copyright (C) 2013 Olivier Goffart <ogoffart@woboq.com>
2 http://woboq.com/blog/property-bindings-in-cpp.html
3
4Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
5associated documentation files (the "Software"), to deal in the Software without restriction,
6including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
7and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
8subject to the following conditions:
9
10The above copyright notice and this permission notice shall be included in all copies or substantial
11portions of the Software.
12
13THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
14NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
16OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
17CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18*/
19
20#pragma once
21
22#include "property.h"
23
24#include <QtCore/QObject>
25#include <QtCore/qmetaobject.h>
26
27class property_qobject_base : public property_base, private QObject {
28
29 QObject *obj;
30 QMetaProperty prop;
31
32public:
33 property_qobject_base(QObject *o, const char *p) : obj(o) {
34 const QMetaObject *mo = o->metaObject();
35 prop = mo->property(mo->indexOfProperty(p));
36 int idx = prop.notifySignalIndex();
37 if (idx >= 0)
38 bindToSignal(idx);
39 }
40
41 void bindToSignal(int signalIndex) {
42 QMetaObject::connect(obj, signalIndex, this, staticMetaObject.methodCount());
43 }
44private:
45 virtual int qt_metacall(QMetaObject::Call c, int idx, void** a) {
46 idx = QObject::qt_metacall(c, idx, a);
47 if (idx < 0)
48 return idx;
49 notify();
50 return idx;
51 }
52
53protected:
54 // virtual void notify() = 0;
55 QVariant getProperty() { accessed(); return prop.read(obj); }
56 bool setProperty(const QVariant &v) { return prop.write(obj, v); }
57};
58
59template <typename T> class property_qobject :
60 public property_qobject_base {
61
62public:
63 property_qobject(::QObject *o, const char *p) : property_qobject_base(o, p) {}
64
65 typedef std::function<T()> binding_t;
66
67 void operator=(const T &t) {
68 setProperty(QVariant::fromValue<T>(t));
69 clearDependencies();
70 //notify();
71 //return *this;
72 }
73 void operator=(const binding_t &b) {
74 binding = b;
75 evaluate();
76 //return *this;
77 }
78
79 T get() {
80 return qvariant_cast<T>(getProperty());
81 }
82
83 void evaluate()
84 {
85 T data;
86 {
87 evaluation_scope scope(this);
88 data = binding();
89 }
90 setProperty(QVariant::fromValue<T>(data));
91 }
92
93 T operator->() { return get(); }
94 T operator()() { return get(); }
95 operator T() { return get(); }
96
97protected:
98 binding_t binding;
99};
100
101