Qt Forum

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

    Update: Forum Guidelines & Code of Conduct

    Solved How to keep QML code seperate from QML UI

    QML and Qt Quick
    3
    4
    1042
    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.
    • S
      scotryder last edited by

      Hi there,

      I,m a new QT developer and want to know how should i keep qml logic separate from qml ui?
      For example one qml file contains all the functions, while ui qml file simplye include function file and references in a way its written in same file like Button {onClicked: functionFromLogicFile()}

      Please advise

      Thanks

      1 Reply Last reply Reply Quote 0
      • Gojir4
        Gojir4 last edited by

        You can import JavaScript file from QML, see here: http://doc.qt.io/qt-5/qtqml-javascript-imports.html

        The Samegame example use this method: http://doc.qt.io/qt-5/qtquick-tutorials-samegame-samegame3-example.html

        Or you can simply put all the functions in a QML component file, and declare it as singleton, to avoid creating a component each time you need to use a function. Here is an example for styling QML: http://wiki.qt.io/Qml_Styling#Approach_2:_Style_Singleton

        1 Reply Last reply Reply Quote 3
        • jpnurmi
          jpnurmi last edited by jpnurmi

          Implement the logic in C++, declare the UI in QML, and glue the pieces together with a minimal amount of JS. You'll get a clean separation and great performance. ;)

          Integrating C++ and QML is a matter of implementing C++ types that expose to QML:

          • properties
          • signals
          • slots / invokable methods

          You can access all these in QML, providing you the necessary tools to communicate between C++ and QML. Notice that there is rarely need to use QObject::findChild() and friends to dig into the hierarchy of QML objects and start manipulating them from C++. Instead, just emit signals from C++ when properties change and relevant events occur.

          The correct way to register a C++ type to QML basically depends on how it should be instantiated:

          • a creatable QML type, such as Item: qmlRegisterType()
          • a QML singleton type, such as LocalStorage, instantiated by the QML engine on demand: qmlRegisterSingletonType()
          • an existing instance created in C++ exposed to QML: QQmlContext::setContextProperty()
          1 Reply Last reply Reply Quote 4
          • S
            scotryder last edited by

            Thank you very much guys, really appreciated :)

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