大家好。我提前为我的英语道歉。 有人可以帮助我吗?我不明白为什么会发生这种情况以及我做错了什么。
我有一个单独的类,其中包含静态常量(当前是字符串常量)
namespace constants {
Q_NAMESPACE
class SharedConstants : public QObject {
Q_OBJECT
Q_PROPERTY(QString Property MEMBER Property CONSTANT)
public:
static inline const QString Property{"MY_PROPERTY_TEXT"};
};
} // namespace constants
在 main.cpp 中,我使用
将其暴露给 QMLqmlRegisterUncreatableType<constants::SharedConstants>(
"Constants", 1, 0, "SharedConstants", "SharedConstants class is not createable");
当我尝试使用 QML 访问我的财产时
import Constants 1.0
...
console.info(SharedConstants.Property)
我得到输出
undefined
。
我假设静态类参数没有以某种方式在 QML 中定义,但我不明白为什么。
最初,我尝试简单地将常量公开给 QML,假设我需要使用
import Constants
。但我没有成功,决定使用该类作为辅助工具。然而,即使在这里,有些东西对我不起作用。请帮忙。如果您知道如何使用 import
将命名空间中的常量公开到 QML,我也将不胜感激。
我正在使用 Qt 5.15.2,C++17 标准。
考虑使用 qmlRegisterSingletonType()。另外,建议 Q_PROPERTY 以小写字母开头。
// sharedconstants.h
#ifndef SHAREDCONSTANTS_H
#define SHAREDCONSTANTS_H
#include <QObject>
#include <QQmlEngine>
#include <QJSEngine>
namespace constants
{
Q_NAMESPACE
class SharedConstants : public QObject
{
Q_OBJECT
public:
explicit SharedConstants(QObject *parent = nullptr);
Q_PROPERTY(QString prop MEMBER prop CONSTANT)
static QObject* singletonProvider(QQmlEngine*, QJSEngine*)
{
return new SharedConstants();
}
private:
static inline const QString prop{"MY_PROPERTY_TEXT"};
};
}
#endif // SHAREDCONSTANTS_H
// main.cpp
qmlRegisterSingletonType<constants::SharedConstants>("Constants", 1, 0, "SharedConstants", &constants::SharedConstants::singletonProvider);
// main.qml
import Constants 1.0
// ...
console.log(SharedConstants.prop);