Qt Quick 구독하기

Qt Quick Controls 을 사용하여 MQTT 토픽을 구독할 수 있는 애플리케이션을 만드세요.

Qt Quick 구독은 QMqttClient 을 QML 유형으로 등록하고 Qt Quick 애플리케이션에서 사용하는 방법을 보여줍니다.

Qt MQTT 는 현재 버전에서 QML API를 제공하지 않습니다. 그러나 모듈의 C++ 클래스를 QML에서 사용할 수 있도록 만들 수 있습니다.

클라이언트 만들기

QMqttSubscription::messageReceived( )에 연결하여 브로커로 전송되는 모든 메시지를 수신합니다:

QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
    : sub(s)
    , client(c)
{
    connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
    m_topic = sub->topic();
}

QMqttClient 클래스를 기본 클래스로 사용하여 QmlMqttClient 클래스를 만듭니다:

QmlMqttClient::QmlMqttClient(QObject *parent)
    : QObject(parent)
{
    connect(&m_client, &QMqttClient::hostnameChanged, this, &QmlMqttClient::hostnameChanged);
    connect(&m_client, &QMqttClient::portChanged, this, &QmlMqttClient::portChanged);
    connect(&m_client, &QMqttClient::stateChanged, this, &QmlMqttClient::stateChanged);
}

subscribe() 함수를 사용하여 구독 개체를 만듭니다:

QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
{
    auto sub = m_client.subscribe(topic, 0);
    auto result = new QmlMqttSubscription(sub, this);
    return result;
}

QMqttMessage 객체를 사용하여 수신된 메시지의 페이로드를 저장합니다:

void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
    emit messageReceived(qmsg.payload());
}

QML에 클래스 등록하기

main.cpp 파일에서 모듈 구독에서 QML 유형 Main을 로드합니다:

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    QObject::connect(
            &engine, &QQmlApplicationEngine::objectCreationFailed, &app,
            []() { QCoreApplication::exit(EXIT_FAILURE); }, Qt::QueuedConnection);

    engine.loadFromModule(u"subscription"_s, u"Main"_s);

이제 Main.qml 파일에서 MqttClient 유형을 사용하여 MQTT 클라이언트를 만듭니다:

    MqttClient {
        id: client
        hostname: hostnameField.text
        port: portField.text
    }

Files:

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.