qtqmlswipeview

Load all QML's from folder


Is it possible to load all QML's from working directory subfolder to SwipeView? Amount of those QML's is unknown and will be changing in time (user may add new and delete old ones), so I think that I also need to reload (refresh) SwipeView when certain Button is clicked. All QML's are different, because they are being created depending on the information which user provides, in Python back-end (just the template is the same).

I've managed to make something like this:

SwipeView {
        id: job_swipe
        width: jobwindow.width/2
        height: jobwindow.height/2
        anchors.verticalCenter: parent.verticalCenter
        anchors.horizontalCenter: parent.horizontalCenter
        orientation: Qt.Vertical

        Component.onCompleted:
            function load_jobs() {
                jobsignals.jobs_to_qmls_slot()
                var i
                var fn
                var fc = (jobsignals.filecount)
                for (i = 0; i<fc; i++) {
                    fn = "jobs/job" + i + ".qml";
                    job_swipe.addPage(job_swipe.createPage(fn))
                }
                //job_swipe.currentIndex = (fc-1)
            }


        function addPage(page) {
            addItem(page)
            page.visible = true
        }

        function createPage(jobfile){
            var component = Qt.createComponent(jobfile);
            var page = component.createObject(job_swipe);
            return page
        }

        function removePage(page) {
            removeItem(page)
            page.visible = false
        }
    }

But removing pages does not working as I want - it removes visually pages, but objects are still there, so when I want to add new page it firstly creates those which I've removed


Solution

  • I would use a FolderListModel to generate a list of .qml files in a folder. Then you can load those with Loaders.

    SwipeView {
        Repeater {
            model: FolderListModel {
                id: folderModel
    
                folder: // Whatever folder you want to search
    
                nameFilters: ["*.qml"]
            }
    
            Loader {
                source: fileUrl
            }
       }
    }
    

    EDIT:

    To refresh the data, I unfortunately don't see a built-in method in FolderListModel to do that. But you should be able to reset the folder value (in a kind of ugly way), like this:

    Button {
        text: "Refresh"
        onClicked: {
            var currentFolder = folderModel.folder
            folderModel.folder = ""                // First clear the folder
            folderModel.folder = currentFolder;    // Then set the folder again
        }
    }