[Interest] Will Qt6 end this enum issue? (or even 5.15?)

Max Paperno max-l at wdg.us
Fri Mar 20 09:44:21 CET 2020



On 3/20/2020 12:53 AM, Jason H wrote:
> That's only part of it.  I want Qt to support it too, mainly for
 > console-qDebug output, but all for use in UI. (Imagine a text element
 > that displays a socket state as it's text.)

I understand, my reply wasn't aimed at your original question.

FWIW, the basic issue seems to be that enums are treated as simple 
integers in QML (the QMetaType on the C++ side is always 
QMetaType::Int).  Otherwise it would be easy to just 
QVariant::toString() them and see the value name like in C++. I couldn't 
come up with any clever way to provide a generic C++ toString() method 
for enum values sent from QML. The actual type info is "lost in 
translation" so to speak.

Of course you could make a toString() helper method for each actual enum 
type (eg. myEnumToString()) and invoke that from QML (from a gadget 
singleton or a context property object, or whatever). Which could then 
use QMetaEnum to deliver the actual name. Seems like quite a bit of 
overhead for something like that, but then again if you have a lot of 
values or they change often, it might be preferable to a value<->name 
lookup table in QML/JS.

OTOH if we're talking purely in QML/JS then you could just use an object 
to store the values and names together. There's a big thread on it at 
StackOverflow[1]. Here's one way which is only a little ugly because the 
Qt ES version doesn't seem to support Symbol().description [2] (yet?):


const Positions = Object.freeze({
   Unspecified: Symbol(1),
   BackFace:    Symbol(2),
   FrontFace:   Symbol(4)
});

const face = Positions.FrontFace;
console.log(face, String(face).slice(7, -1));  // Sumbol(4), 4

switch (face) {
   case Positions.BackFace:
     console.log("The back");
     break;
   case Positions.FrontFace:
     console.log("The front");
     break;
   default:
     console.log("Unknown face");
}

Obviously one could come up with a little helper function/object which 
makes this prettier. And you could make it auto-assign incremental 
values if one isn't provided in the "constructor" (like a C enum does)

Cheers,
-Max


[1]: 
https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript
[2]: 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description



More information about the Interest mailing list