If Qml can do
MyComponent.connect(someJsFunction);
how can I do this on c ??? I need connect JSValue if it isCallable without workarounds. I want to know how it makes qml engine...
QObject::connect(QObject, signal, QJSValue, evaluateFunctionSlot);
CodePudding user response:
This will work. I got the solution from this SO post. That said, I don't know if it aligns with the Qt way of doing it. Their example of invoking a QML method uses QMetaObject::invokeMethod().
main.cpp
#include <QGuiApplication>
#include <QQuickItem>
#include <QQuickView>
class MyClass : public QObject
{
Q_OBJECT
signals:
void cppSignal(const QString &msg);
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view(QUrl(u"qrc:/75069400/main.qml"_qs));
view.show();
QObject *item = view.rootObject();
MyClass myClass;
QObject::connect(&myClass, SIGNAL(cppSignal(QString)),
item, SLOT(callFromCpp(QString)));
emit myClass.cppSignal("this is a test");
return app.exec();
}
#include "main.moc"
main.qml
import QtQuick
Rectangle {
width: 320
height: 240
function callFromCpp(value : string) {
console.log("QML" , value)
}
}
CodePudding user response:
As result the best workaround:
qml
function connect(name, fn){
myObject[name].connect(fn[name]);
}
c
QMetaObject::invokeMethod(MyObject, "connect", Q_ARG(QVariant, "anySlotName"), Q_ARG(QVariant, QVariant::fromValue(data)));