【问题标题】:Qt C++ Signal to QmlQt C++ 信号到 Qml
【发布时间】:2020-07-31 15:00:20
【问题描述】:

我正在尝试在 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 没有收到信号?

【问题讨论】:

    标签: c++ qt qml signals slot


    【解决方案1】:

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

    Connections {
        target: api
    
        onTestStringSended: console.log("recieved")
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多