Qt Quick 出版
MQTTトピックにパブリッシュできるアプリケーションを作成するには、Qt Quick Controls 。
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); }
ラッパー・メソッドは、ラップされたメソッドと同じ名前を持ちます。最も単純なケースでは、1つのメソッドを呼び出すだけです:
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 }
ファイル
© 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.