In my program I have quite a lot of QObject subclasses which are instantiated in QML. Each time I add/remove a new class, I need to add/remove the corresponding call of qmlRegisterType()
in main.cpp. I wonder if I can put the call in the code of the registered class itself. This makes it possible to remove a class by removing its cpp/header file and without altering any other C++ code. Also, I can have my main.cpp clean and don't need to include all the header files of the registered classes.
One way to do that seems to be this:
MyClass.h:
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
private:
static int unused_val;
};
MyClass.cpp:
#include "MyClass.h"
#include <QtQml>
int MyClass::unused_val = qmlRegisterType<MyClass>("my_company", 1, 0, "MyClass");
// some other code
Is there a nicer way? For example, one that doesn't require "unused_val" variable?
Or you could use static objects to do the job for you.
With different types of registration, depending on what you want:
In my opinion more flexible and cleaner than using macros. Usage is simple: first, declare a static member in your class:
Finally, define the member in the .cpp file, just as you did with the macro:
The following solution expands on the method that qCring has above suggested. The solution that was provided suffered from the "static initialization order problem", which was for me reproducible whilst running the code in VS2017. Below is the header file that was used:
The key difference is that the above solution calls upon
qAddPreRoutine
function, which queues each callback to be invoked duringQCoreApplications
's construction.As an example, to register a class (ex:
namespace Common { class Result; }
) as a QML registered type, simple add the following line insideResult
's source file;Likewise to register a class as a none-creatable you simply need to added the following inside their respective source files:
The same structure applies for createable QML types (
QML_REGISTER_CREATABLE_TYPE
), singleton QML types whose live is managed by C++ code (QML_REGISTER_CPP_SINGLETON_TYPE
)), and singleton QML types whose live is managed by the QML engine (QML_REGISTER_JAVASCRIPT_SINGLETON_TYPE
).So far the simplest and cleanest solution I found is to make a C++ macro like this:
MyClass.cpp then needs just this simple line outside of any function:
EDIT: Sometimes this code makes the application to crash in debug mode. See this thread for solution.