简体   繁体   English

为 QML-Usage 返回 QString

[英]returning QString for QML-Usage

idk why, but I can't read a return value of a QString method from.cpp-code in.qml-code, although I did everything logically correct (I'll put only relatable parts of code):我知道为什么,但我无法从.cpp-code in.qml-code 中读取QString方法的返回值,尽管我在逻辑上所做的一切都是正确的(我将只放置代码的相关部分):

.h File: .h 文件:

public:
    Q_INVOKABLE QString displayOnQml();
    QString message;
public slots:
   void updateMessage(const QMqttMessage &msg);

.cpp FIle: .cpp 文件:

connect(m_sub, &QMqttSubscription::messageReceived, this, &mqtt::updateMessage);
connect(m_sub, &QMqttSubscription::messageReceived, this, &mqtt::displayOnQml);
void mqtt::updateMessage(const QMqttMessage &msg)
{
    message=msg.payload();
    qDebug()<<message;
}
QString mqtt::displayOnQml()
{
    return message;
}

.qml File .qml 文件

  Text {
     id: text1
     x: 63
     y: 68
     text: mqttClient.displayOnQml()
     font.pixelSize: 12
  }

(I embedded.cpp-Methodes into.qml as a engine.rootContext()->setContextProperty("mqttClient",mqttClient); , so that I can use other functions as well.) (我将.cpp-Methodes 嵌入到.qml 作为engine.rootContext()->setContextProperty("mqttClient",mqttClient); ,这样我也可以使用其他功能。)

Finally the question: why by debugging I catch the breakpoint in.cpp-File on displayOnQml() ( when I send some data to the topic ), but afterall the object message has "no value", though it was as a public declared?最后的问题是:为什么通过调试我在displayOnQml()上捕获断点 in.cpp-File (当我向主题发送一些数据时),但毕竟 object message “没有价值”,尽管它是public声明的? And still, the simple returns from.cpp-Methodes (such as 1 or 0) are working..而且,来自 .cpp-Methodes 的简单返回(例如 1 或 0)仍然有效。

The Q_INVOKABLE do not create a binding since you cannot know when the string changed. Q_INVOKABLE 不会创建绑定,因为您不知道字符串何时更改。 In this case it is better to create a Q_PROPERTY:在这种情况下,最好创建一个 Q_PROPERTY:

* .cpp * .cpp

class mqtt: ...{
    Q_OBJECT
    // ...
    Q_PROPERTY(QString message READ message NOTIFY messageChanged)
public:
    // ...
    QString message() const;
    // ...
Q_SIGNALS:
    void messageChanged();
    // ...
private:
    QString m_message;
    // ...
};

* .h * .h

void mqtt::updateMessage(const QMqttMessage &msg)
{
    m_message = msg.payload();
    Q_EMIT messageChanged();
}
QString mqtt::message() const{
    return m_message;
}
Text {
    id: text1
    x: 63
    y: 68
    text: mqttClient.message
    font.pixelSize: 12
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM