Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
[SOLVED]Cannot call c++ function from qml
@QGuiApplication app(argc, argv);
QQmlEngine engine; QQmlContext* maincontext = new QQmlContext(engine.rootContext()); MainWindowMC mainMC(maincontext); QQmlComponent component(&engine, QUrl::fromLocalFile("qml/convQML/main.qml")); QQuickWindow* window = qobject_cast<QQuickWindow*> (component.create(maincontext)); window->show(); return app.exec();@
This is my main.cpp.
I pass pointer of context to MainWindowMC.
Here is MainWindowMC:
typeGenerator(); maincontext->setContextProperty("mainwin", this); maincontext->setContextProperty("typemodel", QVariant::fromValue(m_typemodel)); maincontext->setContextProperty("unitmodel", QVariant::fromValue(m_unitmodel));
and the class declaration:
MainWindowMC(QQmlContext*); QStringList typemodel(); void typeGenerator(); Q_INVOKABLE void unitGenerator(QString type);
It seems I have done everything - registered object in context, made Q_INVOKABLE function-but I cannot call the funtion from QML. It throws "TypeError: Object [object Object] has no method 'unitGenerator'"
What am I doing wrong?
Optionaly, this is how I try to use the function in QML:
@ onCurrentTextChanged: mainwin.unitGenerator(typebox.currentText)
Wow, this is really strange way of instantiating QML engine and view. Why are you doing this in such a complicated manner?
Is your MainWindowMC a QObject? Have you added the Q_OBJECT macro?
bq. Wow, this is really strange way of instantiating QML engine and view. Why are you doing this in such a complicated manner?Is your MainWindowMC a QObject? Have you added the Q_OBJECT macro?
MainWindowMC is dreived from a class which on the other hand derives from QObject. I had a an issue with Q_OBJECT. The thing is mainM has Q_OBJECT macro (base class of MainWindowMC). -When I add Q_OBJECT in MainWindowMC, it throws some strange errors but I think Q_OBJECT moves to MainWindowMC ad it is derived from mainM- I have added Q_OBJECT macro but still the same problem.
Which part is complicated? I have just started using QML, so I don't know much about it. I think everything is as it should be. I make engine, give the pointer of context to a class(I don't want to make my main.cpp too long) and I create component with that context?
Qnoobish last edited by
I think first you have to load the QML file, then try to get the rootContext and set the property to use your class object with invokable functions.
QQmlComponent component(&engine, QUrl::fromLocalFile("qml/convQML/main.qml"));
QQmlContext* maincontext = new QQmlContext(engine.rootContext());
Well for me the easy way is this, but everybody has their own:
// from memory, sorry for any errors
QQuickView *view = new QQuickView();
MainWindowMC *mainMC = new MainWindowMC();
Anyways ppl, sorry for wasting your time, it is not my fault. I cleaned and rebuilt and it started working (probably some pre-compilation issues)