PDA

View Full Version : How to fetch files one by one from FolderListModel in QML?



TheIndependentAquarius
5th March 2016, 11:07
Intention of the following code is to let the user select a folder of photos, and then display those photos one by one.


PhotoViewer.qml


import QtQuick 2.0
import QtQuick.Dialogs 1.0 // FileDialog
import Qt.labs.folderlistmodel 2.1 // FolderListModel

Item
{
id: head
property url path

property int i: 0

height: 500; width: 500
FileDialog
{
id: photoDirectoryFileDialog
title: "Select the photo directory:"
selectFolder: true
visible: true
height: parent.height; width: parent.width
onAccepted: head.path = fileUrl
}

ListView
{
FolderListModel
{
id: folderModel
folder: photoDirectoryFileDialog.fileUrl
nameFilters: ["*.jpg"]
}

Component
{
id: fileDelegate
Text { text: fileName }
}

model: folderModel
delegate: fileDelegate
}

// Show photos
Image
{
id: image
source: ""
}

MouseArea
{
anchors.fill: parent
onClicked:
{
console.log ("fsdfsdf: " + i + " --- " + photoDirectoryFileDialog.fileUrl + "/" + folderModel.get (i, folderModel.fileName))
image.source = photoDirectoryFileDialog.fileUrl + "/" + folderModel.get (i, folderModel.folder.fileName)
i++
}
}
}


----------


main.qml


import QtQuick 2.4
import QtQuick.Window 2.2

Window
{
id: rootWindow
visible: true
height: 700; width: height

PhotoViewer
{
height: rootWindow.height; width: rootWindow.width
}
}


Output:


QML debugging is enabled. Only use this in a safe environment.
qml: fsdfsdf: 0 --- file:///home/***/Pictures/Wallpapers/undefined
qrc:/PhotoViewer.qml:43:5: QML Image: Cannot open: file:///home/***/Pictures/Wallpapers/undefined
qml: fsdfsdf: 1 --- file:///home/***/Pictures/Wallpapers/undefined
qml: fsdfsdf: 2 --- file:///home/***/Pictures/Wallpapers/undefined

As you can see in the output, I am receiving "undefined" as file name in the output. How to fetch files one by one from FolderListModel in QML?

anda_skoa
5th March 2016, 12:12
Look at the documentation of FolderListModel.get()
The second argument is a string that tells get() which property of the entry you want.

You are passing "undefined", since FolderListModel does not have a property "fileName" (in your log output) nor does string have a property "fileName" (in the next line).

Cheers,
_

TheIndependentAquarius
7th March 2016, 06:45
Thanks, you reminded me that the problem was that I had forgotten that the second variable of the function get is a string (http://doc.qt.io/qt-5/qml-qt-labs-folderlistmodel-folderlistmodel.html#get-method).

That means that the property `fileName` has to be passed in "", as shown below.



console.log ("fsdfsdf: " + folderModel.count + " --- " + photoDirectoryFileDialog.fileUrl + "/" + folderModel.get (folderModel.count-1, "fileName"))
image.source = photoDirectoryFileDialog.fileUrl + "/" + folderModel.get (folderModel.count-1, "fileName")