Reputation: 176
I have a c++ class like this:
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;}
};
And I use it in other c++ classes and it's Ok. Now, I want to use P1 and P2 in my qml file too. So, I have in main.cpp:
qmlRegisterType<MyClass>("com.MyClass", 1, 0, "MyClass");
And in my qml file:
import com.MyClass 1.0
.
.
.
console.log(MyClass.P1);
console.log(MyClass.getP2);
After running code, console show undefined
for both of them! And MyClass.getP2()
cause following error:
TypeError: Property 'getP2' of object [object Object] is not a function
How can I use of P1 and P2 in qml?
Solution:
Based on @pooya13 answer, I put this in 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;
});
So, I could use MyClass.P1
in qml file.
Upvotes: 0
Views: 1591
Reputation: 2691
As folibis pointed out, it seems that you are using MyClass
as a QML singleton (qmlRegisterSingletonInstance
or qmlRegisterSingletonType
):
// Does not need to be instantiated in QML (`MyClass` refers to registered singleton object)
console.log(MyClass.prop)
console.log(MyClass.getProp())
whereas you are registering it as a regular type:
// Needs to be instantiated in QML (`MyClass` refers to registered type)
MyClass {
Component.onCompleted: {
console.log(prop)
console.log(getProp())
}
}
Upvotes: 1