Search code examples
qmlqt-quick

Reading n random files from a folder in Qt Quick


I'm writing my first Qt Quick application and I'm having lots of trouble doing things that are simple in other environments. I want to display n random images from a folder. For this purpose I'm using FolderListModel, but the trouble is that I don't see any methods to access list of files directly. So here's my hackish approach:

  • Use FolderListModel to read files
  • Use Text component as delegate
  • onTextChanged of Text component gets the filename (this part works) and adds it to some ListModel
  • randomize the ListModel and then use it to display files

I have many problems and questions, but first of all, what is the sane way to do this (please make it so that the list part doesn't have to be written in c++)?

There are 2 problems for now - I can't figure out how to access the ListModel from Text component; and I can' t figure out how to make the ListModel public/accessible from another component that will display the images.

Below is the code:

import QtQuick 1.0
import Qt.labs.folderlistmodel 1.0

ListView {
    width: 200; height: 300


    FolderListModel {
        folder: "file:///C:/somefolder"
        id: folderModel
        nameFilters: ["*.jpg"]
    }

    Component {
        id: fileDelegate
        Text { id: intext
               text: fileName
               //the next line fails, Can't find variable: anotherModel
               onTextChanged: anotherModel.append([{name: intext.text}]
             )
        }
    }

    model: folderModel
    delegate: fileDelegate


    ListModel {
          id: anotherModel
      }
}

Solution

  • Your code almost works for me. I get the error "QML ListModel: append: value is not an object". This is because you append arrays. If you remove the brackets in line

    anotherModel.append([{name: intext.text}]) 
    

    it works. To make anotherModel a public property write it as

    property ListModel anotherModel: ListModel {}