1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the examples of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include "qquickfolderlistmodel.h"
44 #include "fileinfothread_p.h"
45 #include "fileproperty_p.h"
46 #include <qqmlcontext.h>
51 class QQuickFolderListModelPrivate
53 Q_DECLARE_PUBLIC(QQuickFolderListModel)
56 QQuickFolderListModelPrivate(QQuickFolderListModel *q)
58 sortField(QQuickFolderListModel::Name), sortReversed(false), showDirs(true), showDirsFirst(false), showDots(false), showOnlyReadable(false)
60 nameFilters << QLatin1String("*");
64 QQuickFolderListModel *q_ptr;
67 FileInfoThread fileInfoThread;
68 QList<FileProperty> data;
69 QHash<int, QByteArray> roleNames;
70 QQuickFolderListModel::SortField sortField;
71 QStringList nameFilters;
76 bool showOnlyReadable;
78 ~QQuickFolderListModelPrivate() {}
83 void _q_directoryChanged(const QString &directory, const QList<FileProperty> &list);
84 void _q_directoryUpdated(const QString &directory, const QList<FileProperty> &list, int fromIndex, int toIndex);
85 void _q_sortFinished(const QList<FileProperty> &list);
89 void QQuickFolderListModelPrivate::init()
91 Q_Q(QQuickFolderListModel);
92 qRegisterMetaType<QList<FileProperty> >("QList<FileProperty>");
93 q->connect(&fileInfoThread, SIGNAL(directoryChanged(QString, QList<FileProperty>)),
94 q, SLOT(_q_directoryChanged(QString, QList<FileProperty>)));
95 q->connect(&fileInfoThread, SIGNAL(directoryUpdated(QString, QList<FileProperty>, int, int)),
96 q, SLOT(_q_directoryUpdated(QString, QList<FileProperty>, int, int)));
97 q->connect(&fileInfoThread, SIGNAL(sortFinished(QList<FileProperty>)),
98 q, SLOT(_q_sortFinished(QList<FileProperty>)));
102 void QQuickFolderListModelPrivate::updateSorting()
104 Q_Q(QQuickFolderListModel);
106 QDir::SortFlags flags = 0;
109 case QQuickFolderListModel::Unsorted:
110 flags |= QDir::Unsorted;
112 case QQuickFolderListModel::Name:
115 case QQuickFolderListModel::Time:
118 case QQuickFolderListModel::Size:
121 case QQuickFolderListModel::Type:
128 emit q->layoutAboutToBeChanged();
131 flags |= QDir::Reversed;
133 fileInfoThread.setSortFlags(flags);
136 void QQuickFolderListModelPrivate::_q_directoryChanged(const QString &directory, const QList<FileProperty> &list)
138 Q_Q(QQuickFolderListModel);
143 emit q->rowCountChanged();
144 emit q->folderChanged();
148 void QQuickFolderListModelPrivate::_q_directoryUpdated(const QString &directory, const QList<FileProperty> &list, int fromIndex, int toIndex)
150 Q_Q(QQuickFolderListModel);
154 if (data.size() > list.size()) {
155 //File(s) removed. Since I do not know how many
156 //or where I need to update the whole list from the first item.
158 q->beginRemoveRows(parent, fromIndex, toIndex);
160 q->beginInsertRows(parent, fromIndex, list.size()-1);
162 emit q->rowCountChanged();
163 } else if (data.size() < list.size()) {
164 //qDebug() << "File added. FromIndex: " << fromIndex << " toIndex: " << toIndex << " list size: " << list.size();
165 //File(s) added. Calculate how many and insert
166 //from the first changed one.
167 toIndex = fromIndex + (list.size() - data.size()-1);
168 q->beginInsertRows(parent, fromIndex, toIndex);
171 emit q->rowCountChanged();
172 QModelIndex modelIndexFrom = q->createIndex(fromIndex, 0);
173 QModelIndex modelIndexTo = q->createIndex(toIndex, 0);
174 emit q->dataChanged(modelIndexFrom, modelIndexTo);
176 //qDebug() << "File has been updated";
177 QModelIndex modelIndexFrom = q->createIndex(fromIndex, 0);
178 QModelIndex modelIndexTo = q->createIndex(toIndex, 0);
180 emit q->dataChanged(modelIndexFrom, modelIndexTo);
184 void QQuickFolderListModelPrivate::_q_sortFinished(const QList<FileProperty> &list)
186 Q_Q(QQuickFolderListModel);
189 q->beginRemoveRows(parent, 0, data.size()-1);
193 q->beginInsertRows(parent, 0, list.size()-1);
200 \qmlclass FolderListModel QQuickFolderListModel
201 \ingroup qtquick-models
202 \brief The FolderListModel provides a model of the contents of a file system folder.
204 FolderListModel provides access to information about the contents of a folder
205 in the local file system, exposing a list of files to views and other data components.
207 \note This type is made available by importing the \c Qt.labs.folderlistmodel module.
208 \e{Elements in the Qt.labs module are not guaranteed to remain compatible
211 \b{import Qt.labs.folderlistmodel 1.0}
213 The \l folder property specifies the folder to access. Information about the
214 files and directories in the folder is supplied via the model's interface.
215 Components access names and paths via the following roles:
228 Additionally a file entry can be differentiated from a folder entry via the
233 Various properties can be set to filter the number of files and directories
234 exposed by the model.
236 The \l nameFilters property can be set to contain a list of wildcard filters
237 that are applied to names of files and directories, causing only those that
238 match the filters to be exposed.
240 Directories can be included or excluded using the \l showDirs property, and
241 navigation directories can also be excluded by setting the \l showDotAndDotDot
244 It is sometimes useful to limit the files and directories exposed to those
245 that the user can access. The \l showOnlyReadable property can be set to
248 \section1 Example Usage
250 The following example shows a FolderListModel being used to provide a list
251 of QML files in a \l ListView:
253 \snippet qml/folderlistmodel.qml 0
255 \section1 Path Separators
257 Qt uses "/" as a universal directory separator in the same way that "/" is
258 used as a path separator in URLs. If you always use "/" as a directory
259 separator, Qt will translate your paths to conform to the underlying
262 \sa {QML Data Models}
265 QQuickFolderListModel::QQuickFolderListModel(QObject *parent)
266 : QAbstractListModel(parent), d_ptr(new QQuickFolderListModelPrivate(this))
268 Q_D(QQuickFolderListModel);
269 d->roleNames[FileNameRole] = "fileName";
270 d->roleNames[FilePathRole] = "filePath";
271 d->roleNames[FileBaseNameRole] = "fileBaseName";
272 d->roleNames[FileSuffixRole] = "fileSuffix";
273 d->roleNames[FileSizeRole] = "fileSize";
274 d->roleNames[FileLastModifiedRole] = "fileModified";
275 d->roleNames[FileLastReadRole] = "fileAccessed";
276 d->roleNames[FileIsDirRole] = "fileIsDir";
280 QQuickFolderListModel::~QQuickFolderListModel()
284 QVariant QQuickFolderListModel::data(const QModelIndex &index, int role) const
286 Q_D(const QQuickFolderListModel);
289 if (index.row() >= d->data.size())
295 rv = d->data.at(index.row()).fileName();
298 rv = d->data.at(index.row()).filePath();
300 case FileBaseNameRole:
301 rv = d->data.at(index.row()).baseName();
304 rv = d->data.at(index.row()).suffix();
307 rv = d->data.at(index.row()).size();
309 case FileLastModifiedRole:
310 rv = d->data.at(index.row()).lastModified().date().toString(Qt::ISODate) + " " + d->data.at(index.row()).lastModified().time().toString();
312 case FileLastReadRole:
313 rv = d->data.at(index.row()).lastRead().date().toString(Qt::ISODate) + " " + d->data.at(index.row()).lastRead().time().toString();
316 rv = d->data.at(index.row()).isDir();
324 QHash<int, QByteArray> QQuickFolderListModel::roleNames() const
326 Q_D(const QQuickFolderListModel);
331 \qmlproperty int FolderListModel::count
333 Returns the number of items in the current folder that match the
336 int QQuickFolderListModel::rowCount(const QModelIndex &parent) const
338 Q_D(const QQuickFolderListModel);
340 return d->data.size();
343 QModelIndex QQuickFolderListModel::index(int row, int , const QModelIndex &) const
345 return createIndex(row, 0);
349 \qmlproperty string FolderListModel::folder
351 The \a folder property holds a URL for the folder that the model is
354 The value is a URL expressed as a string, and must be a \c file: or \c qrc:
355 URL, or a relative URL.
357 By default, the value is an invalid URL.
359 QUrl QQuickFolderListModel::folder() const
361 Q_D(const QQuickFolderListModel);
362 return d->currentDir;
365 void QQuickFolderListModel::setFolder(const QUrl &folder)
367 Q_D(QQuickFolderListModel);
369 if (folder == d->currentDir)
372 QString localPath = QQmlFile::urlToLocalFileOrQrc(folder);
373 QString resolvedPath = QDir::cleanPath(QUrl(localPath).path());
377 //Remove the old path for the file system watcher
378 if (!d->currentDir.isEmpty())
379 d->fileInfoThread.removePath(d->currentDir.path());
381 d->currentDir = folder;
383 QFileInfo info(resolvedPath);
384 if (!info.exists() || !info.isDir()) {
387 emit rowCountChanged();
391 d->fileInfoThread.setPath(resolvedPath);
396 \qmlproperty string QQuickFolderListModel::rootFolder
398 When the rootFolder is set, then this folder will
399 be threated as the root in the file system, so that
400 you can only travers sub folders from this rootFolder.
402 QUrl QQuickFolderListModel::rootFolder() const
404 Q_D(const QQuickFolderListModel);
408 void QQuickFolderListModel::setRootFolder(const QUrl &path)
410 Q_D(QQuickFolderListModel);
415 QString localPath = QQmlFile::urlToLocalFileOrQrc(path);
416 QString resolvedPath = QDir::cleanPath(QUrl(localPath).path());
418 QFileInfo info(resolvedPath);
419 if (!info.exists() || !info.isDir())
422 d->fileInfoThread.setRootPath(resolvedPath);
428 \qmlproperty url FolderListModel::parentFolder
430 Returns the URL of the parent of of the current \l folder.
432 QUrl QQuickFolderListModel::parentFolder() const
434 Q_D(const QQuickFolderListModel);
436 QString localFile = d->currentDir.toLocalFile();
437 if (!localFile.isEmpty()) {
439 #if defined(Q_OS_WIN)
445 localFile = dir.path();
447 int pos = d->currentDir.path().lastIndexOf(QLatin1Char('/'));
450 localFile = d->currentDir.path().left(pos);
452 return QUrl::fromLocalFile(localFile);
456 \qmlproperty list<string> FolderListModel::nameFilters
458 The \a nameFilters property contains a list of file name filters.
459 The filters may include the ? and * wildcards.
461 The example below filters on PNG and JPEG files:
465 nameFilters: [ "*.png", "*.jpg" ]
469 \note Directories are not excluded by filters.
471 QStringList QQuickFolderListModel::nameFilters() const
473 Q_D(const QQuickFolderListModel);
474 return d->nameFilters;
477 void QQuickFolderListModel::setNameFilters(const QStringList &filters)
479 Q_D(QQuickFolderListModel);
480 d->fileInfoThread.setNameFilters(filters);
481 d->nameFilters = filters;
484 void QQuickFolderListModel::classBegin()
488 void QQuickFolderListModel::componentComplete()
490 Q_D(QQuickFolderListModel);
492 if (!d->currentDir.isValid() || d->currentDir.toLocalFile().isEmpty() || !QDir().exists(d->currentDir.toLocalFile()))
493 setFolder(QUrl(QLatin1String("file://")+QDir::currentPath()));
497 \qmlproperty enumeration FolderListModel::sortField
499 The \a sortField property contains field to use for sorting. sortField
502 \li Unsorted - no sorting is applied.
503 \li Name - sort by filename
504 \li LastModified - sort by time modified
505 \li Size - sort by file size
506 \li Type - sort by file type (extension)
511 QQuickFolderListModel::SortField QQuickFolderListModel::sortField() const
513 Q_D(const QQuickFolderListModel);
517 void QQuickFolderListModel::setSortField(SortField field)
519 Q_D(QQuickFolderListModel);
520 if (field != d->sortField) {
521 d->sortField = field;
526 int QQuickFolderListModel::roleFromString(const QString &roleName) const
528 Q_D(const QQuickFolderListModel);
529 return d->roleNames.key(roleName.toLatin1(), -1);
533 \qmlproperty bool FolderListModel::sortReversed
535 If set to true, reverses the sort order. The default is false.
539 bool QQuickFolderListModel::sortReversed() const
541 Q_D(const QQuickFolderListModel);
542 return d->sortReversed;
545 void QQuickFolderListModel::setSortReversed(bool rev)
547 Q_D(QQuickFolderListModel);
549 if (rev != d->sortReversed) {
550 d->sortReversed = rev;
556 \qmlmethod bool FolderListModel::isFolder(int index)
558 Returns true if the entry \a index is a folder; otherwise
561 bool QQuickFolderListModel::isFolder(int index) const
564 QModelIndex idx = createIndex(index, 0);
566 QVariant var = data(idx, FileIsDirRole);
575 \qmlproperty bool FolderListModel::showDirs
577 If true, directories are included in the model; otherwise only files
580 By default, this property is true.
582 Note that the nameFilters are not applied to directories.
586 bool QQuickFolderListModel::showDirs() const
588 Q_D(const QQuickFolderListModel);
592 void QQuickFolderListModel::setShowDirs(bool on)
594 Q_D(QQuickFolderListModel);
596 d->fileInfoThread.setShowDirs(on);
601 \qmlproperty bool FolderListModel::showDirsFirst
603 If true, if directories are included in the model they will
604 always be shown first, then the files.
606 By default, this property is false.
609 bool QQuickFolderListModel::showDirsFirst() const
611 Q_D(const QQuickFolderListModel);
612 return d->showDirsFirst;
615 void QQuickFolderListModel::setShowDirsFirst(bool on)
617 Q_D(QQuickFolderListModel);
619 d->fileInfoThread.setShowDirsFirst(on);
620 d->showDirsFirst = on;
625 \qmlproperty bool FolderListModel::showDotAndDotDot
627 If true, the "." and ".." directories are included in the model; otherwise
630 By default, this property is false.
634 bool QQuickFolderListModel::showDotAndDotDot() const
636 Q_D(const QQuickFolderListModel);
640 void QQuickFolderListModel::setShowDotAndDotDot(bool on)
642 Q_D(QQuickFolderListModel);
644 if (on != d->showDots) {
645 d->fileInfoThread.setShowDotDot(on);
650 \qmlproperty bool FolderListModel::showOnlyReadable
652 If true, only readable files and directories are shown; otherwise all files
653 and directories are shown.
655 By default, this property is false.
659 bool QQuickFolderListModel::showOnlyReadable() const
661 Q_D(const QQuickFolderListModel);
662 return d->showOnlyReadable;
665 void QQuickFolderListModel::setShowOnlyReadable(bool on)
667 Q_D(QQuickFolderListModel);
669 if (on != d->showOnlyReadable) {
670 d->fileInfoThread.setShowOnlyReadable(on);
675 \qmlmethod QVariant QQuickFolderListModel::get(int idx, const QString &property) const
677 Get the folder property for the given index. The following properties
691 QVariant QQuickFolderListModel::get(int idx, const QString &property) const
693 int role = roleFromString(property);
694 if (role >= 0 && idx >= 0)
695 return data(index(idx, 0), role);
700 #include "moc_qquickfolderlistmodel.cpp"