Synthesize Qt properties
There are some utils that I use in most of my Qt projects. I’m a bit fed up of copy-pasting those every time I need something, so I created a project containing tools that are of frequent use when I write Qt apps, regardless of the type of app.
The only interesting tool I added yet is the synthesizer of Q_PROPERTY’s. You can use the macros:
L_RW_PROP L_RO_PROP
to synthétise props, with getter, setter and notifications. Each macro is overloaded: with 3 params, you do not have initialisation, adding a 4th param, also initialises the variable to the provided value. Also, I frequently need QObject that are just containers of properties, to be used in QML. I added these two macros to spare some lines:
L_BEGIN_CLASS(<class_name>) L_END_CLASS
A class like:
class Fraction : public QObject<br> { Q_OBJECT Q_PROPERTY(double numerator READ numerator WRITE setNumerator NOTIFY numeratorChanged) Q_PROPERTY(double denominator READ denominator WRITE setDenominator NOTIFY denominatorChanged) public: Fraction(QObject* parent = nullptr) : QObject(parent) {}<br> double numerator() const { return m_numerator; } double denominator() const { return m_denominator; } public slots: void setNumerator(double numerator) { if (m_numerator == numerator) return; m_numerator = numerator; emit numeratorChanged(numerator); } void setDenominator(double denominator) { if (m_denominator == denominator) return; m_denominator = denominator; emit denominatorChanged(denominator); } signals: void numeratorChanged(double numerator); void denominatorChanged(double denominator); private: double m_numerator; double m_denominator; };
can simply be written as:
L_BEGIN_CLASS(Fraction) L_RW_PROP(double, numerator, setNumerator) L_RW_PROP(double, denominator, setDenominator) L_END_CLASS
I’m sure there are other similar approaches out there, but if you need it, you can simply add this repo as a submodule like I do: https://github.com/carlonluca/lqtutils.
Bye! 😉