我有一个类似这样的c++类:
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString P1 READ getP1)
Q_PROPERTY(QString P2 READ getP2)
public:
inline explicit MyClass(QObject *parent = nullptr) : QObject(parent) {}
inline static const QString P1 = "something1";
inline static const QString P2 = "something2";
Q_INVOKABLE inline static QString getP1() {return P1;}
Q_INVOKABLE inline static QString getP2() {return P2;}
};
我在其他c++类中使用它,这很好。现在,我也想在qml文件中使用P1和P2。所以,我在main.cpp:
qmlRegisterType<MyClass>("com.MyClass", 1, 0, "MyClass");
在我的qml文件中:
import com.MyClass 1.0
.
.
.
console.log(MyClass.P1);
console.log(MyClass.getP2);
运行完代码后,控制台将为它们显示undefined
!MyClass.getP2()
导致以下错误:
TypeError:object〔object object〕的属性"getP2"不是函数
如何在qml中使用P1和P2?
解决方案:
根据@pooya13的回答,我把这个放在main.cpp:中
qmlRegisterSingletonType<MyClass>("com.MyClass", 1, 0, "MyClass",[](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
MyClass *example = new MyClass();
return example;
});
所以,我可以在qml文件中使用MyClass.P1
。
正如folibis所指出的,您似乎正在使用MyClass
作为QML单例(qmlRegisterSingletonInstance
或qmlRegisterSingletonType
(:
// Does not need to be instantiated in QML (`MyClass` refers to registered singleton object)
console.log(MyClass.prop)
console.log(MyClass.getProp())
而您将其注册为常规类型:
// Needs to be instantiated in QML (`MyClass` refers to registered type)
MyClass {
Component.onCompleted: {
console.log(prop)
console.log(getProp())
}
}