Qt Quick 出版物
Qt Quick コントロールを使用して、MQTTトピックにデータを公開できるアプリケーションを作成します。

Qt Quick 「パブリケーション」では、QMqttClient をQMLタイプとして登録し、Qt Quick アプリケーションでそれを使用する方法について解説します。
Qt MQTT 現在のバージョンでは、QML API は提供されていません。ただし、このモジュールの C++ クラスを QML から利用できるようにすることは可能です。
クライアントの作成
QMqttClient をメンバとして持つラッパークラスQmlMqttClient を作成します:
private:
Q_DISABLE_COPY(QmlMqttClient)
QMqttClient m_client;
};コンストラクタ内で、ラッパーメソッドをQMqttClient のメソッドに接続します:
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);
}ラッパーメソッドは、ラップされるメソッドと同じ名前を持ちます。最も単純なケースでは、それは単一のメソッド呼び出しに過ぎません:
void QmlMqttClient::connectToHost()
{
m_client.connectToHost();
}また、ラップメソッドにいくつかの追加機能を拡張することで、カスタマイズすることも可能です:
voidQmlMqttClient::setPort(intnewPort)
{
if(newPort< 0||newPort>std::numeric_limits<quint16>::max()) {
qWarning() << "Trying to set invalid port number";
return;
}
m_client.setPort(static_cast<quint16>(newPort));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"publication"_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.