Skip to content

Instantly share code, notes, and snippets.

@Rolias
Last active September 27, 2023 21:58
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save Rolias/48d453a0490d36090193 to your computer and use it in GitHub Desktop.
Save Rolias/48d453a0490d36090193 to your computer and use it in GitHub Desktop.
Qt Auto Property Macros
#pragma once
#include <QObject>
//See Gist Comment for description, usage, warnings and license information
#define AUTO_PROPERTY(TYPE, NAME) \
Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed ) \
public: \
TYPE NAME() const { return a_ ## NAME ; } \
void NAME(TYPE value) { \
if (a_ ## NAME == value) return; \
a_ ## NAME = value; \
emit NAME ## Changed(value); \
} \
Q_SIGNAL void NAME ## Changed(TYPE value);\
private: \
TYPE a_ ## NAME;
#define READONLY_PROPERTY(TYPE, NAME) \
Q_PROPERTY(TYPE NAME READ NAME CONSTANT ) \
public: \
TYPE NAME() const { return a_ ## NAME ; } \
private: \
void NAME(TYPE value) {a_ ## NAME = value; } \
TYPE a_ ## NAME;
@tackelua
Copy link

tackelua commented Aug 16, 2019

Hi, thanks for your great working

I have some ideas for updating the file.

  • Use reference in function WRITE in AUTO_PROPERTY
    void NAME(const TYPE& value)

  • Remove function WRITE in READONLY_PROPERTY
    void NAME(TYPE value) {a_ ## NAME = value; }

  • Add define READ_PROPERTY with the Q_SIGNAL for qml can get the notify when property changed in C++.
    QML can not change the property.

You can see details in https://gist.github.com/tackelua/bcae0e346fc98184ba7a044315fd0a4c/revisions#diff-b6a69a742adff907546e80f3703e301a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment