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 }
ファイル
© 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.