QML element don't update with C++ Q_PROPERTY



  • Hi,

    I created a small code to show my problem. The element "text", clicking on the item "Change Author" menu, was to update and display the text "Marcelo". I'm trying to use the example of documentation for using Q_PROPERTY but it is not working. See the code below. What am I doing wrong?

    book.h
    @#ifndef BOOK_H
    #define BOOK_H

    #include <QObject>
    #include <QString>

    class book : public QObject
    {
    Q_OBJECT
    Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
    public:
    Q_INVOKABLE void getData();

        QString author() const;
        void setAuthor(const QString &);
    
    signals:
        void authorChanged();
    
    private:
        QString m_author;
    

    };

    #endif // BOOK_H@

    book.cpp
    @#include "book.h"

    void book::getData()
    {
    this->setAuthor("Marcelo");
    }

    QString book::author() const
    {
    return m_author;
    }

    void book::setAuthor(const QString &a)
    {
    if (m_author != a)
    {
    m_author = a;
    emit authorChanged();
    }
    }@

    main.qml
    @import QtQuick 2.2
    import QtQuick.Controls 1.1
    import book 1.0

    ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    BOOK_REG {
        id: book_reg
    }
    
    menuBar: MenuBar {
        Menu {
            title: qsTr("File")
    
            MenuItem {
                text: qsTr("Change Author")
                onTriggered: book_reg.getData();
            }
    
            MenuItem {
                text: qsTr("Exit")
                onTriggered: Qt.quit();
            }
        }
    }
    
    Text {
        text: book_pro.author
        anchors.centerIn: parent
        Component.onCompleted: {
            book_pro.author = "John"
        }
    }
    

    }@

    main.cpp
    @#include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QtQml>
    #include "book.h"

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    book b;
    qmlRegisterType<book>("book", 1, 0, "BOOK_REG");
    
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("book_pro", &b);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    
    return app.exec();
    

    }
    @



  • You are not changing the value of text. You need to set the id for the text element.

    One you click on the onTriggered, you need to set the text for text element. Just try the following.

    @MenuItem {
    text: qsTr("Change Author")
    onTriggered: {var value = book_reg.getData();
    authorme.text = value

               }  
            }
    

    Text {
    id : authorme
    text: book_pro.author
    anchors.centerIn: parent
    Component.onCompleted: {
    book_pro.author = "John"
    }
    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.