Improving Qt’s properties.

July 01

I have known Qt for about 9 years now. My first encounter with Qt was as a normal user who was exploring Linux to find out what the fuss was all about. With KDE I got my first experience of Qt. But I have only very recently started to use Qt as a development tool, and I have been very happy about that. Makes life easy, with Qt being ported to Symbian, Meego the gates are open for developers to make money. Since I like to experiment with all the platforms no matter who they are from, I also played around with Objective-C on iPhone some while ago.

While Qt offers many many nice features which make Objective-C look like from stone age. Objective-C has some nice features as well, one I mentioned in my previous post, which Qt already solves rather nicely and in a better way as one of the commenter pointed out. Objective-C and Qt are quite similar in a sense that they provide improvements on top of an already existing language. Qt with meta object compiler and Obj-C with something similar.

So back to the point, I now use Q_PROPERTY macro in my QObjects based classes a lot:

class Person : public QObject
Q_PROPERTY(QString name READ name WRITE setName)

void setName(const QString& aName) { iName = aName; }
QString name() const { return iName; }

QString iName;

Now consider this Objective-C code:

// person.h
@interface Person : NSObject
NSString* name;
@property (nonatomic, retain) NSString* name; // same as Q_OBJECT 

// person.m:
@implementation Person
@synthesize name; // this generates getter/setter in the .m file

// rest of the code ...

So do you see what I see ? In the Objective-C version of the code I don’t have to write the getter and setter methods, whereas in Qt i have to. I think all the information to automatically implement the getter and setter functions is already in the Q_PROPERTY macro, may be the moc compiler can go ahead and also generate the getter and setter methods for us ?

Be Sociable, Share!

Posted by on July 1, 2010 in nokia, objective c, programming, Qt

1 Comment

One response to “Improving Qt’s properties.

  1. Don

    October 7, 2010 at 1:47 pm

    One thing about writing your own getters and setters is that you can have more behaviour than just setting/getting. For example you can choose not to emit a modified signal if setting the value to the same value, you can make the get perform some lazy evaluation with caching, etc.

    Not saying moc _couldn’t_ check if you had your own setters/getters and otherwise add them (“public” I suppose?), but it’s never bothered me to be honest.

    And of course moc would most likely make the getter return “const QString &” so how would you return the “QString” like in your example? :)


Leave a Reply

Your email address will not be published. Required fields are marked *