[Development] [QML] Assigning ints to enumeration properties

Alan Alpert 416365416c at gmail.com
Wed Mar 6 20:23:49 CET 2013

On Wed, Mar 6, 2013 at 3:11 AM, Laszlo Papp <lpapp at kde.org> wrote:
> On Wed, Mar 6, 2013 at 9:48 AM, Olivier Goffart <olivier at woboq.com> wrote:
>> This is not a warning, this is an error in C++
>> enum Foo { A ,  B };
>> Foo bar = 1; // error: invalid conversion from ‘int’ to ‘Foo’
>> int blah = bar; // No warning. unless you use enum class then it is a
>> error.
> At least, I can second that even with msvc variants, but perhaps Alan meant
> -fpermissive or so.

Yes - although I thought -fpermissive was on by default for gcc (but
it isn't, now that I've checked). Whoops.

>> I think implicit casts is *not* a good idea.
>> Allowing explicit casts should be good.
> That would be a bit uglier in QML than a static or function type explicit
> cast like in C++ unless there is a nice trick not to make map, object,
> mapper function or so for enums with many values. Perhaps parseInt() or
> something similar? I would not know.
> If there is no nice trick, I would suggest allowing it (perhaps with a
> warning on the console?) because I do not wish to maintain such code if I
> know what I am doing. :)

Unfortunately neither explicit casts nor a warning on the console
would work well.

We can't have explicit casts because the scripts are in JavaScript,
which is dynamically typed. The only static typing is on QML objects,
so the function would only make sense when assigning to a property. In
most cases then, you'd just make the property type int. The problem is
when trying to have a good C++ API for the item as well; in C++ you
want enum types and then they can cast to int if they want. So either
you compromise your C++ API (use ints) or you compromise your QML API
(use enums, but have to use hacky workarounds to cast ints).

The workarounds bit ties into a couple of performance related aspects.
You can currently work around it by taking a known enum (like
Qt::AlignLeft = 1), and adding a number. This forms a script which can
be assigned to an enum type, but it's ugly and a bad performance
precedent to use scripts this way. The QML 1 engine is also very slow
at using enums, so using ints instead would help tune up existing QML
1 applications (while they port to QML 2 of course, which has improved
enum performance already).

The problem with a warning on the console is that these are emitted
every time the application runs. So if you've written your application
correctly and are happy with it, the user shouldn't be seeing the
console flooded with warnings. This is why QML needs to be
conservative with the compile warnings, compared to C++, they should
all be considered runtime warnings.

Alan Alpert

More information about the Development mailing list