Yat C++ 信号到 Yaml

Qt C++ Signal to Qml

我正在尝试在 Qml 中捕获 C++ Qt 信号。我能够发送信号,并且在 Qt 中捕获 Qml 信号也能正常工作;但是,我无法在 Qml 中捕捉到 Qt 信号。

我需要哪个QObject::connect?

最小 main.cpp:

    #include <QtGui/QGuiApplication>
    #include <QtQml/QQmlApplicationEngine>
    #include <QQmlContext>
    #include <QQuickWindow>
    
    #include "qmlcppapi.h"

    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
        qmlRegisterType<QmlCppApi>("com.handleQmlCppApi",1,0,"HandleQmlCppApi");
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/qml/qmlfile.qml"));
        QmlCppApi api;
        engine.rootContext()->setContextProperty("api", &api);
        engine.load(url);
        QObject::connect(&api, &QmlCppApi::testStringSended,
                         &api, &QmlCppApi::printTestString);
        return app.exec();
    }

最小gmlcppapi.hpp: 插槽仅用于显示是否发出信号

    #ifndef QMLCPPAPI_H
    #define QMLCPPAPI_H
    
    #include <QObject>
    #include <QDebug>
    
    class QmlCppApi : public QObject
    {
        Q_OBJECT
    
    public:
        Q_INVOKABLE void postTestString(QString TestString) {
            qDebug() << "cpp: recieved";
            emit testStringSended(TestString);
        }
    
    public slots:
        void printTestString(QString TestString) {
            qDebug() << "cpp: sended";
        }
    
    signals:
        void testStringSended(QString TestString);
    };
    
    #endif // QMLCPPAPI_H

最小qmlfile.qml: ToggleButton 应该执行 cpp 函数 testStringSended。并且 printTestString 正在发射一个应该触发 onTestStringSended

的发射器
    import QtQuick 2.2
    import QtQuick.Window 2.1
    import QtQuick.Controls 1.4
    import QtQuick.Controls.Styles 1.4
    import QtQuick.Extras 1.4
    import com.handleQmlCppApi 1.0
    
    Window {
        visible: true
        ToggleButton {
            onClicked: {
                console.log("send")
                api.postTestString("TestString")
            }
        }
    
        HandleQmlCppApi {
            onTestStringSended: console.log("recieved")
        }
    }

输出:

qml: send
cpp: recieved
cpp: sended

为什么我的Qml收不到信号?

您创建了两个 QmlCppApi 实例。一个在 main.cpp 中,您称之为 api,另一个在 QML 中,它是未命名的 HandleQmlCppApi 对象。你只需要其中之一。要捕获来自 api 的信号,您需要一个 Connections 对象,如下所示:

Connections {
    target: api

    onTestStringSended: console.log("recieved")
}