Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    Solved How to read variable values between pages on different QML files?

    QML and Qt Quick
    2
    3
    307
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      arjun30 last edited by

      In a QML project, I am using a StackView to switch between different pages. However, something inside one of the files, called Game.qml needs to know the value and when a variable is changed in the main.qml file. So far, I have been using a external JS file to store the variables "globally". However, the problem is I cannot use an automatic signal handler to find out when the value is changed in the main.qml file.
      Does anyone know any alternate solutions so I can change variables from two seperate QML files with ease? I am very new to Qt (sorry if this is a obvious question). Right now, my application is purely in qml with very little c++, but any solution (even a c++) would help.

      ODБOï 1 Reply Last reply Reply Quote 0
      • ODБOï
        ODБOï @arjun30 last edited by ODБOï

        @arjun30 said in How to read variable values between pages on different QML files?:

        Game.qml needs to know the value and when a variable is changed in the main.qml

        Globally defined properties in main.qml are accessibles for all the qml components

        //main.qml
        ApplicationWindow {
            id:root
            property var test : 0
        
        //Game.qml
        Item {
            property var val: root.test
            onValChanged: console.log(val)
        
        

        but i believe this is not recommended approach.

        You can use QML Singleton

        You also can have a c++ class with a Q_PROPERTY, you set its value from main.qml, and access it where you need
        https://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html#exposing-properties

        A 1 Reply Last reply Reply Quote 2
        • A
          arjun30 @ODБOï last edited by

          I used the Q_PROPERTY approach and it worked great! Thanks for all your help.

          1 Reply Last reply Reply Quote 0
          • First post
            Last post