diff options
author | Dennis Oberst <[email protected]> | 2022-12-12 12:24:21 +0100 |
---|---|---|
committer | Dennis Oberst <[email protected]> | 2023-02-14 13:32:13 +0100 |
commit | 213e932e138d460159487a624838aa7d3bcffb4a (patch) | |
tree | e36ea07b76a9e6dfbcee3a5026deefa22fd10a71 /examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp | |
parent | 05d713a2baf238f4a89e6f78e23156e51150adb6 (diff) |
Add File System Explorer example
This example shows the customization of Qt Quick Controls by
implementing a simple file system explorer. Using a C++ model, entries
are visualized in a TreeView, and text files can be read.
Fixes: QTBUG-108289
Change-Id: I966dcf65e40d3b727889dc14c65edd0ffcc1b878
Reviewed-by: Mitch Curtis <[email protected]>
Diffstat (limited to 'examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp')
-rw-r--r-- | examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp b/examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp new file mode 100644 index 0000000000..45b47737f5 --- /dev/null +++ b/examples/quickcontrols/filesystemexplorer/filesystemmodel.cpp @@ -0,0 +1,48 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include "filesystemmodel.h" + +#include <QMimeDatabase> +#include <QStandardPaths> + +FileSystemModel::FileSystemModel(QObject *parent) : QFileSystemModel(parent) +{ + setRootPath(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); +} + +int FileSystemModel::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return 1; +} + +QString FileSystemModel::readFile(const QString &filePath) +{ + // Don't issue errors for an empty path, as the initial binding + // will result in an empty path, and that's OK. + if (filePath.isEmpty()) + return {}; + + QFile file(filePath); + + const QMimeDatabase db; + const QMimeType mime = db.mimeTypeForFile(QFileInfo(file)); + + if (file.size() >= 2'000'000) + return tr("File size is too big.\nYou can read files up to %1 MB.").arg(2); + + // Check if the mimetype is supported and return the content. + const auto mimeTypesForFile = mime.parentMimeTypes(); + for (const auto &m : mimeTypesForFile) { + if (m.contains("text", Qt::CaseInsensitive) + || mime.comment().contains("text", Qt::CaseInsensitive)) { + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return tr("Error opening the File!"); + + QTextStream stream(&file); + return stream.readAll(); + } + } + return tr("Filetype not supported!"); +} |