[Development] RFC: Improved Q_ENUM

Matthew Woehlke mw_triad at users.sourceforge.net
Wed Feb 18 18:16:58 CET 2015


On 2015-02-18 11:44, Olivier Goffart wrote:
> On Wednesday 18 February 2015 11:25:54 Matthew Woehlke wrote:
>> Sorry to jump in so late, but... *THIS IS AWESOME!* Converting enums to
>> strings and vice versa is very common, but I'm not aware of a generic
>> solution to the problem until now. (Yes, bidirectional; as mentioned,
>> use in settings, UI, file export etc. are all existing non-debug uses.
>> Not that the QDebug support isn't killer by itself :-).)
>>
>> I have two questions, though:
>>
>> 1. How does this interact with QSettings? If I directly pass an enum to
>> e.g. QSettings::setValue, is it written as an int or an enum (I guess
>> int)? What about if I use QVariant::fromValue (i.e. so the variant type
>> is the enum)?
> 
> I have not tried QSettings yet, but since it works with QVariant it should 
> work.

Sure, I'd expect it to work, also :-). What I meant was, does it get
written as an integer, or as a string?

>> 2. If I have a QString that I want to convert to the enum, is there a
>> way to test if the string matches an enum value? (Also, is the
>> conversion case sensitive?)
> 
> Yes, the conversion is case sensitive. It works using QMetaEnum.
> In Qt 5.5 you can do
> QMetaEnum::fromType<MyObject::MyEnum>().keyToValue("ABCD");

That's rather... unfortunate. For the QVariant case (e.g. QSettings, UI
guts) it's maybe tolerable. For the explicit keyToValue, would it be
possible to add a case insensitive option? (I'm thinking of e.g. reading
from user input, where it is desirable to follow a 'liberal in what you
accept' policy.)

>> Because I am lazy :-), can you give us a brief summary of how string
>> conversion works (or does it?) for flags?
> 
> Flags, are not yet supported within QVariant. Maybe for 5.6

Fair enough. I'd originally thought that was the case, but when you
later mentioned Q_FLAG, I was less sure. (Obviously this gets into
interesting cases like, how do you convert to/from string when the flag
value is a combination of enum values and does not exactly match an enum
value? Solvable, but requires putting a little more thought into it.)

Related: do you gracefully handle unknown enum values?

Also, If I have a QString that I want to convert to the enum, is there a
way to test if the string matches an enum value? (I don't mean some
particular value, in case that was unclear. Rather, how do you handle
failure of keyToValue because the string doesn't match any enum value?
Does it rely on returning a magic value that must not be a valid enum
value to be detectable? Is there an optional 'okay' parameter? Is there
a way to test first if the conversion would be valid?)

-- 
Matthew




More information about the Development mailing list