Qt Quick サブスクリプション
Qt Quick コントロールを使用して、MQTTトピックを購読できるアプリケーションを作成します。

Qt Quick 「Subscription」では、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);
}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 ファイルで、subscriptionモジュールから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
}ファイル:
© 2026 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.