Exposing already defined enum to QML
-
I have an enum which is already define as below:
// Defines.h file namespace com { enum class BookType { SMALL = 0, BIG, UNKOWN }; } Above enum doesn't have a Q_NAMESPACE declared. I created the QObject class to expose enum to QML // Book.h file #include "Defines.h" namespace com { Q_NAMESPACE Q_ENUM_NS(BookType) } namespace ui { class Book: public QObject { Q_OBJECT QML_ELEMENT QML_SINGLETON Q_PROPERTY(com::BookType type READ type WRITE setType NOTIFY onTypeChanged) .... } } // Main.qml Button { onClicked: { console.log(Book.BookType.BIG) // gives undefined console.log(Book.type) // gives 1 } }
How can access BookType enum be used in qml ?
-
What about:
console.log(BookType.BIG)
-
An easy but ugly way would be to change
com
into a stuct with Q_GADGET.Alternatively you should be able to register the enum manually Qt5-way:
qRegisterMetaType<com::BookType>();
-
enums are always a mess, basically the general idea to have a clean namespace with enums doesn't work with QML.
I'm always just going for the slightly ugly but entirely functional solution to make the namespace a QObject instead. Example:
https://codeberg.org/Flowee/pay/src/branch/master/src/WalletEnums.hThen in your C++ you just need: qmlRegisterType<WalletEnums>("something.or.other", 1, 0, "MyEnums");
Then in your QML you need to import the first argument (something.or.other) and you can use your values in that file without problems.
-
@TomZ said in Exposing already defined enum to QML:
enums are always a mess, basically the general idea to have a clean namespace with enums doesn't work with QML.
It does work fine with namespaces. Q_ENUM needs to be made in the scope where the enum was defined though, it doesn't work with an already defined enum. And this requirement exists for both object/gadgets and namespaces.
The code you linked would have been fine with a namespace.Also don't use
qmlRegister***
in Qt 6,QML_***
are preferred.