在注册的类本身中调用 qmlRegisterType() [英] call qmlRegisterType() in the registered class itself
问题描述
在我的程序中,我有很多在 QML 中实例化的 QObject 子类.每次添加/删除一个新的类,都需要在main.cpp中添加/删除qmlRegisterType()
的对应调用.我想知道是否可以将调用放在注册类本身的代码中.这使得可以通过删除其 cpp/头文件而不更改任何其他 C++ 代码来删除类.另外,我可以让我的 main.cpp 干净,不需要包含注册类的所有头文件.
一种方法似乎是这样的:
MyClass.h:
class MyClass : public QObject{Q_OBJECT上市:MyClass(QObject *parent = 0);私人的:静态 int 未使用_val;};
MyClass.cpp:
#include "MyClass.h"#include <QtQml>int MyClass::unused_val = qmlRegisterType("my_company", 1, 0, "MyClass");//其他一些代码
有更好的方法吗?例如,一个不需要unused_val"变量的?
到目前为止,我发现的最简单、最干净的解决方案是制作这样的 C++ 宏:
#define QML_REGISTER(a) static int used_val = qmlRegisterType("my_uri", 1, 0, #a)
MyClass.cpp 然后在任何函数之外只需要这简单的一行:
QML_REGISTER(MyClass);
EDIT:有时此代码会使应用程序在调试模式下崩溃.请参阅此线程以获取解决方案.>
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?
So far the simplest and cleanest solution I found is to make a C++ macro like this:
#define QML_REGISTER(a) static int unused_val = qmlRegisterType<a>("my_uri", 1, 0, #a)
MyClass.cpp then needs just this simple line outside of any function:
QML_REGISTER(MyClass);
EDIT: Sometimes this code makes the application to crash in debug mode. See this thread for solution.
这篇关于在注册的类本身中调用 qmlRegisterType()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!