1

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);
Jo Mw
  • 23
  • 5

2 Answers2

0

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)
    }
}
iam_peter
  • 3,205
  • 1
  • 19
  • 31
  • Thanks a lot for reply, but it is not QJSValue. I need connect QObject signal to QJSValue slot as like as QJSValue.call(). I know how to do an workaround but it's not interesting. – Jo Mw Jan 12 '23 at 07:21
0

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)));
Jo Mw
  • 23
  • 5