Consider this simple enum class:
#include <QObject>
class BookTypes : public QObject
{
Q_GADGET
Q_ENUMS(AllBooksType)
public:
enum AllBooksType{
eMagazine,
eReference,
eTextBook,
eThesis
};
signals:
public slots:
};
Type registration in main()
qmlRegisterUncreatableType<BookTypes>("trial", 1, 0, "BookTypes",
"Don't create qml instance for BookTypes");
And this is sample QML:
Rectangle {
id: rect
x: 100; y: 100
width: 100
height: 70
color: "PowderBlue"
border.color: "RoyalBlue"
border.width: 1
radius: 3
MouseArea{
x: 0; y: 0
height: parent.height
width: parent.width
property int bt: BookTypes.eTextBook //perfect. now bt is 2
onClicked: {
console.debug("old book type:- ")
console.debug(bt) //prints 2
console.debug("selected book type:- ")
bt = BookTypes.eReference //gives error - why ?
console.debug(BookTypes.eReference) //prints 'undefined'
console.debug(bt)
}
}
}
This means that the enum is properly exposed, since it initializes bt
successfully in
property int bt: BookTypes.eTextBook
What I don't understand is: why it is not accessible when I try to replace value of bt
in handler:
bt = BookTypes.eReference //gives error - why ?
How do I pass such an enum
as an argument of Q_INVOKABLE
method, for instance:
console.debug(BookTypes.eReference) //prints 'undefined'
SomeObj.someCPPMethod(BookTypes.eReference) // sends 'undefined' and defaults to 0
You should always use QObject::setProperty(), QQmlProperty or QMetaProperty::write() to change a QML property value, to ensure the QML engine is made aware of the property change.
Using the enumeration Type in QMLThe enumeration type is a representation of a C++ enum type. It is not possible to refer to the enumeration type in QML itself; instead, the int or var types can be used when referring to enumeration values from QML code. See also QML Value Types and Enumeration Attributes.
Exposing Properties. A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived or Q_GADGET class are accessible from QML.
A QtObject is a QML representation of the QObject element. This can be seen in Qt source code here where the QML base types are registered: ... void QQmlEnginePrivate::registerBaseTypes(const char *uri, int versionMajor, int versionMinor) { ... qmlRegisterType<QObject>(uri,versionMajor,versionMinor,"QtObject"); ...
Taken from the docs:
Note: The names of enum values must begin with a capital letter in order to be accessible from QML.
Which does beg the question: Why does it work in the property binding? I've no idea, probably a Qt bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With