【问题标题】:Qt 5.4/QML: How do I correctly implement a custom C++ class as a global QML singleton instance and implement code for its signals (in QML)?Qt 5.4/QML:如何正确地将自定义 C++ 类实现为全局 QML 单例实例并为其信号实现代码(在 QML 中)?
【发布时间】:2015-01-27 12:18:36
【问题描述】:

我有一个小 C++ 类,我想在 QML 中注册,这样我就可以从 QML 代码中访问它,并为 QML 开发人员提供一个安全的 API - 同时将复杂的东西保持在“幕后”并从用户的角度隐藏起来QML。

到目前为止,我已经编写了这样的自定义类:


main.cpp

static QObject *myapi_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)
    MyApi *apiInstance = new MyApi();
    return apiInstance;
}


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qmlRegisterSingletonType<MyApi>("com.example.myapi", 1, 0, "MyApi", myapi_singletontype_provider);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("http://server.com/myqml.qml")));
    return app.exec();
}

MyApi.h

#ifndef MyApi_H
#define MyApi_H

#include <QObject>
#include <QtNetwork>
#include <QtCore/QDebug>
#include <QtCore/QObjectList>

class MyApi : public QObject
{
    Q_OBJECT

public:
    explicit MyApi(QObject *parent = 0);
    ~MyApi();


signals:
    void downloadStarted(const QString &uuid);
    void downloadFinished(const QString &uuid);
    void downloadError(const QString &uuid, const QString &errorText);
    void downloadProgress(const QString &uuid, const float progress);

public slots:
    void downloadArchiveInBackground(const QString &uuid);


};

#endif // MyApi_H

MyApi.cpp

#include "MyApi.h"

void MyApi::downloadArchiveInBackground(const QString &uuid) {
    // I would like to connect these signals to JS methods in QML!
    emit downloadStarted(uuid);
    emit downloadProgress(uuid, 0.3);
}

QML(伪)

MyApi {
    id: myapi
    onDownloadStarted: {
        console.log("OK STARTED")
        dialogDownload.open()
    }
}

实际上我不知道如何实现这一点。我知道我在这里创建了一个实例,并且不需要使用单例,因为它是单例实例 - 但我需要一些关于如何在 QML 中实现从 C++ 发出的信号处理程序的指针。

【问题讨论】:

    标签: javascript c++ qt qml


    【解决方案1】:

    你可以使用ConnectionQML类型。

    import com.example.myapi 1.0
    
    Connections {
        target: MyApi
        onDownloadFinished: //do something
    }
    

    【讨论】:

    • 这看起来不错。从未见过Connections,我会调查一下,谢谢!
    • 这就是我要找的!惊人的!有一些+1。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多