Nov 4, 2014

Qt Auto Property

Automating the Boilerplate Code

I was recently involved in a discussion on the Qt project forums regarding the Qt property system and the amount of additional code that needs to be written for standard properties that use trivial getters and setters. While there is a MEMBER  variable association it would appear to make your private implementation details public. It seems quite possible that using it could restrict future changes to your implementation details if you don’t want to break existing uses of your code. I find this antithetical to the purpose of creating properties in the first place.

I was thinking Qt could offer something much like C#’s auto properties. If you’ve never seen them you can set a trivial property like this:

public bool CustomerId {get;  set; }

My latest course, Fundamentals of Qt Quick is now available on Pluralsight.

I made a suggestion on the Qt tracker system that Qt add a similar feature, but was told it was not possible. However, the responder pointed me in the direction of a solution indicating that I would write my own macro to do this. So I did. Even though I’ve been programming since Lady Lovelace was a lass I’ve never been overly fond of C macros and I’ve avoided them. However, this seems like a good reason to use them so I thought I would give it a go. I wasn’t after the exact syntax just the lack of clutter. You use these macros like this:

AUTO_PROPERTY(QString, myProperty)

READONLY_PROPERTY(double, myValue)

No need to write getters, setters, the signal or the backing variable. If you change your mind later, you can replace the AUTO_PROPERTY with a Q_PROPERTY or whatever you want without breaking your interface.

I’m posting the code for these macros to a public gist with two purposes in mind. First I’m hoping that any C macro experts out there might see ways to improve them and contribute their code. Secondly, I’m hoping others might find them useful and give them some exercise to validate them.  On the gist site I added an extensive comment to document the macros. If you’ve never used a Gist , you can either use git or a similar tool to download the code and work with it under repository control or you can use the embedded view below, click on the RAW button and just copy and paste the macro.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.