[Development] RFC: Improved Q_ENUM

Olivier Goffart olivier at woboq.com
Mon Dec 15 14:38:00 CET 2014


Hello,

I have been working on some improvements to moc and the meta type system to 
improve Q_ENUM. Those changes are targeting Qt 5.5

You can see the list of change there in the q_gadget topic (I put the changes 
in that topic even if it is an orthogonal changes to the Q_GADGET changes that 
are already in)

https://codereview.qt-project.org/#/q/status:open+project:qt/qtbase+branch:dev+topic:q_gadget,n,z

This is something that I have actually started working on a long time ago.
The problem I wanted to solve was to show the actual string of the value when 
using qDebug with enum values that are registered with Q_ENUMS
I tried many different option, and finally got a working solution, but it does 
require small changes, so I added a new macro Q_ENUM to keep compatibility

Q_ENUM is almost the same as Q_ENUMS, but:
 - It can only contains one enum at the time, while you can put several in a
    Q_ENUMS
 - It need to be placed *after* the enum declaration in the class.

Q_ENUMS is still existing and do not regress. But if you use Q_ENUM instead, 
you get:
 - Using it with qDebug prints the actual string of the value.
 - It is automatically registered as a QMetaType and you do not need 	
   Q_REGISTER_METATYPE anymore
 - It is also possible to get the related QMetaObject from the QMetaType.
 - You can get the QMetaEnum using the new QMetaEnum::fromType<T>()
 - a QVariant containing that enum can automatically be converted to QString
   or QByteArray with the value name. Also, if the QVariant contains a QString
   or a QByteArray with a value name, it can be converted to the enum type.
   (This could be useful for QML as well, as you should not need to
   artificially expose the enums to QML anymore)

At first, I wanted to deprecate Q_ENUMS and show a warning when Q_ENUMS is 
used. But because it is a bit of work to move to Q_ENUM, I just did not put a 
warning yet.

I can already hear the resistant to change nay-sayer "I like to put my Q_ENUMS 
at the beginning of the class with all the meta-stuff".  Well, Q_ENUM can go 
directly after the enum in question, so it stays together.
This is also where you would put things like Q_DECLARE_FLAGS

Any opinions or comments?

You can review the patches. (First patch is there: 
 https://codereview.qt-project.org/89415/ )

-- 
Olivier 

Woboq - Qt services and support - http://woboq.com - http://code.woboq.org



More information about the Development mailing list