QML : Navigation between qml pages from design perception

c++, qml, qt, qt-quick

Solution

Here is the simplest solution in plain QML, using a configurable page list (like a model) + a Repeater + Loader items to not load everything at startup (lazy instanciation) and not destroy a page after hiding it (to not have to reload it if we come back to it) :

import QtQuick 1.1

Rectangle {
    id: main_rectangle;
    width: 360;
    height: 640;

    // Put the name of the QML files containing your pages (without the '.qml')
    property variant pagesList  : [
        "Page1",
        "Page2",
        "Page3",
        "Page4",
        "Page5"
    ];

    // Set this property to another file name to change page
    property string  currentPage : "Page1";

    Repeater {
        model: pagesList;
        delegate: Loader {
            active: false;
            asynchronous: true;
            anchors.fill: parent;
            visible: (currentPage === modelData);
            source: "%1.qml".arg(modelData)
            onVisibleChanged:      { loadIfNotLoaded(); }
            Component.onCompleted: { loadIfNotLoaded(); }

            function loadIfNotLoaded () {
                // to load the file at first show
                if (visible && !active) {
                    active = true;
                }
            }
        }
    }
}

Hope it helps !

Problem

We need to develop a QtQuick project, where we have about 100 screens. I had tried to make a demo project for the navigation which has three screens on button click. I had used the concepts of 'States' in the navigation between the pages. Initially I tried the same using 'Loader' but loader was not able to retain the previous state of page, it was re-loading the entire page during the navigation. Below is the code snippet of main.qml ``` // import QtQuick 1.0 // to target S60 5th Edition or Maemo 5 import QtQuick 1.1 Rectangle { id:main_rectangle width: 360 height: 640 Page1{ id:page1 } Page2{ id:page2 } Page3{ id:page3 } states: [ State { name: "page2" PropertyChanges { target: page3; visible:false; } PropertyChanges { target: page1; visible:false; } PropertyChanges { target: page2; visible:true; } }, State { name: "page1" PropertyChanges { target: page3; visible:false; } PropertyChanges { target: page2; visible:false; } PropertyChanges { target: page1; visible:true; } }, State { name: "page3" PropertyChanges { target: page1; visible:false; } PropertyChanges { target: page2; visible:false; } PropertyChanges { target: page3; visible:true; } } ] } ``` This runs well with the small POC with three screens, but its not feasible to define states for 100 screens. From designing aspect we concluded to make a C++ controller we controls the states, visibility of various pages. Need suggestions how to implement the 'State' logic in C++.

Original source