I found a great example of how to use C enums in QML. But I can't seem to figure out why the qRegisterMetaType line is necessary. The following code runs just fine with AND without the following lines:
qRegisterMetaType<Status>("Status");
and
using Status = StatusClass::Value;
QML does not throw an error when you leave out those lines. What is the significance of qRegisterMetaType<>() when accesing a C enum via a typedef?
statusclass.h:
#ifndef STATUSCLASS_H
#define STATUSCLASS_H
#include <QObject>
class StatusClass
{
Q_GADGET
public:
enum class Value {
Null,
Ready,
Loading,
Error
};
Q_ENUM(Value)
private:
explicit StatusClass() {};
};
using Status = StatusClass::Value;
#endif // STATUSCLASS_H
main.cpp:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qRegisterMetaType<Status>("Status");
qmlRegisterUncreatableType<StatusClass>("qml.guide", 1, 0, "Status", "Not creatable");
}
main.qml:
import QtQuick 2.9
import QtQuick.Window 2.12
import qml.guide 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log(Status.Loading);
}
}
CodePudding user response:
The qRegisterMetaType
function essentially allows a typedef
or alias to be assigned to a QVariant
. QVariants
are important in QML because they used to store the arguments from signals and slots, and also get values from the QMetaProperty
system.
In the case of this enum, which essentially aliases the int
type, it will simply mean that the type will shows up as Status
instead, which is useful for debugging, etc.
CodePudding user response:
If you want to share only enums to QML the qmlRegisterUncreatableType is enough.
qmlRegisterUncreatableType - This template function registers the C type in the QML system with the name qmlName. While the type has a name and a type, it cannot be created, and the given error message will result if creation is attempted. This is useful where the type is only intended for providing attached properties or enum values.
qRegisterMetaType - Registers the type name typeName for the type T. Returns the internal ID used by QMetaType. Any class or struct that has a public default constructor, a public copy constructor and a public destructor can be registered. After a type has been registered, you can create and destroy objects of that type dynamically at run-time. This function is useful only for registering an alias, so share objects to QML.