Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate setters and getters, and define Q_PROPERTY() with the C++ preprocessor

I'm designing a QT4 class. So far my class looks like this:

class GIHNode : public QObject, public QGraphicsItem
{

Q_OBJECT
Q_INTERFACES( QGraphicsItem )
[...]
public:
void setInteger(int);
int getInteger();

[..]
private:
int Integer; Q_PROPERTY(int Integer READ getInteger WRITE setInteger)
// Definition I'd like to replace

The setters and getters are implemented like this:
void GIHNode::setInteger(int x){Integer=x;}
int GIHNode::getInteger(){return Integer;}

I'd like to define a macro that does all this work for me. I have tried this for the definition of a variable and the text inside Q_PROPERTY:

#define ID(x) x
#define STR_HELPER(x,y) ID(x)y
#define STRGET(x) STR_HELPER(get,x)
#define STRSET(x) STR_HELPER(set,x)
#define EXPORTEDVAR(type,varname) type varname; Q_PROPERTY(type varname READ STRGET(varname) WRITE STRSET(varname))

When I replace the line:

int Integer; Q_PROPERTY(int Integer READ getInteger WRITE setInteger)

with

EXPORTEDVAR(int,Integer)

the macro is correctly pre-processed, and it's replaced with:

int Integer; Q_PROPERTY(int Integer READ getInteger WRITE setInteger)

I have checked manually with cpp. The code compiles, but I can't get the property of an instance of this class. I'm using the metaobject (from QT4 moc) of an instance of this class to retrieve the properties, but I can't find it. I suppose this has something to do with the pre-processor, but I don't know how to investigate this.

like image 224
alecail Avatar asked Oct 23 '22 06:10

alecail


1 Answers

The moc doesn't expand macros with arguments (See moc Limitations), so it doesn't see your Q_PROPERTY statements.

like image 71
alexisdm Avatar answered Nov 07 '22 12:11

alexisdm