Skip to content

PythonQt.Qt.QDir

QDir

PythonQtInstanceWrapper object

Native bases: PythonQtInstanceWrapper

Supplemental documentation: Qt 5 reference:

Detailed Description

A QDir is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system. It can also be used to access Qt's resource system.

Qt uses "/" as a universal directory separator in the same way that "/" is used as a path separator in URLs. If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system.

A QDir can point to a file using either a relative or an absolute path. Absolute paths begin with the directory separator (optionally preceded by a drive specification under Windows). Relative file names begin with a directory name or a file name and specify a path relative to the current directory.

Examples of absolute paths:

QDir("/home/user/Documents")
QDir("C:/Users")

On Windows, the second example above will be translated to C:\Users when used to access files.

Examples of relative paths:

QDir("images/landscape.png")

You can use the isRelative() or isAbsolute() functions to check if a QDir is using a relative or an absolute file path. Call makeAbsolute() to convert a relative QDir to an absolute one.

Note: Paths starting with a colon (:) are always considered absolute, as they denote a QResource.

Navigation and Directory Operations

A directory's path can be obtained with the path() function, and a new path set with the setPath() function. The absolute path to a directory is found by calling absolutePath().

The name of a directory is found using the dirName() function. This typically returns the last element in the absolute path that specifies the location of the directory. However, it can also return "." if the QDir represents the current directory.

QDir("Documents/Letters/Applications").dirName() // "Applications"
QDir().dirName()                                 // "."

The path for a directory can also be changed with the cd() and cdUp() functions, both of which operate like familiar shell commands. When cd() is called with the name of an existing directory, the QDir object changes directory so that it represents that directory instead. The cdUp() function changes the directory of the QDir object so that it refers to its parent directory; i.e. cd("..") is equivalent to cdUp().

Directories can be created with mkdir(), renamed with rename(), and removed with rmdir().

You can test for the presence of a directory with a given name by using exists(), and the properties of a directory can be tested with isReadable(), isAbsolute(), isRelative(), and isRoot().

The refresh() function re-reads the directory's data from disk.

Files and Directory Contents

Directories contain a number of entries, representing files, directories, and symbolic links. The number of entries in a directory is returned by count(). A string list of the names of all the entries in a directory can be obtained with entryList(). If you need information about each entry, use entryInfoList() to obtain a list of QFileInfo objects.

Paths to files and directories within a directory can be constructed using filePath() and absoluteFilePath(). The filePath() function returns a path to the specified file or directory relative to the path of the QDir object; absoluteFilePath() returns an absolute path to the specified file or directory. Neither of these functions checks for the existence of files or directory; they only construct paths.

QDir directory("Documents/Letters");
QString path = directory.filePath("contents.txt");
QString absolutePath = directory.absoluteFilePath("contents.txt");

Files can be removed by using the remove() function. Directories cannot be removed in the same way as files; use rmdir() to remove them instead.

It is possible to reduce the number of entries returned by entryList() and entryInfoList() by applying filters to a QDir object. You can apply a name filter to specify a pattern with wildcards that file names need to match, an attribute filter that selects properties of entries and can distinguish between files and directories, and a sort order.

Name filters are lists of strings that are passed to setNameFilters(). Attribute filters consist of a bitwise OR combination of Filters, and these are specified when calling setFilter(). The sort order is specified using setSorting() with a bitwise OR combination of SortFlags.

You can test to see if a filename matches a filter using the match() function.

Filter and sort order flags may also be specified when calling entryList() and entryInfoList() in order to override previously defined behavior.

The Current Directory and Other Special Paths

Access to some common directories is provided with a number of static functions that return QDir objects. There are also corresponding functions for these that return strings:

QDir QString Return Value
current() currentPath() The application's working directory
home() homePath() The user's home directory
root() rootPath() The root directory
temp() tempPath() The system's temporary directory

The setCurrent() static function can also be used to set the application's working directory.

If you want to find the directory containing the application's executable, see QCoreApplication::applicationDirPath().

The drives() static function provides a list of root directories for each device that contains a filing system. On Unix systems this returns a list containing a single root directory "/"; on Windows the list will usually contain C:/, and possibly other drive letters such as D:/, depending on the configuration of the user's system.

Path Manipulation and Strings

Paths containing "." elements that reference the current directory at that point in the path, ".." elements that reference the parent directory, and symbolic links can be reduced to a canonical form using the canonicalPath() function.

Paths can also be simplified by using cleanPath() to remove redundant "/" and ".." elements.

It is sometimes necessary to be able to show a path in the native representation for the user's platform. The static toNativeSeparators() function returns a copy of the specified path in which each directory separator is replaced by the appropriate separator for the underlying operating system.

Examples

Check if a directory exists:

QDir dir("example");
if (!dir.exists())
    qWarning("Cannot find the example directory");

(We could also use the static convenience function QFile::exists().)

Traversing directories and reading a file:

QDir dir = QDir::root();                 // "/"
if (!dir.cd("tmp")) {                    // "/tmp"
    qWarning("Cannot find the \"/tmp\" directory");
} else {
    QFile file(dir.filePath("ex1.txt")); // "/temporary/ex1.txt"
    if (!file.open(QIODevice::ReadWrite))
        qWarning("Cannot create the file %s", file.name());
}

A program that lists all the files in the current directory (excluding symbolic links), sorted by size, smallest first:

#include <QDir>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QDir dir;
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Size | QDir::Reversed);

    QFileInfoList list = dir.entryInfoList();
    std::cout << "     Bytes Filename" << std::endl;
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10)
                                                .arg(fileInfo.fileName()));
        std::cout << std::endl;
    }
    return 0;
}

Platform Specific Issues

On Android, some limitations apply when dealing with content URIs:

  • Access permissions might be needed by prompting the user through the QFileDialog which implements Android's native file picker.
  • Aim to follow the Scoped storage guidelines, such as using app specific directories instead of other public external directories. For more information, also see storage best practices.
  • Due to the design of Qt APIs (e.g. QFile), it's not possible to fully integrate the latter APIs with Android's MediaStore APIs.

Source: https://doc.qt.io/archives/qt-5.15/qdir.html

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
AccessMask attribute Any (shared captured text)
AllDirs attribute Any (shared captured text)
AllEntries attribute Any (shared captured text)
CaseSensitive attribute Any (shared captured text)
Dirs attribute Any (shared captured text)
DirsFirst attribute Any (shared captured text)
DirsLast attribute Any (shared captured text)
Drives attribute Any (shared captured text)
Executable attribute Any (shared captured text)
Files attribute Any (shared captured text)
Filter attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
Filters attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
Hidden attribute Any (shared captured text)
IgnoreCase attribute Any (shared captured text)
LocaleAware attribute Any (shared captured text)
Modified attribute Any (shared captured text)
Name attribute Any (shared captured text)
NoDot attribute Any (shared captured text)
NoDotAndDotDot attribute Any (shared captured text)
NoDotDot attribute Any (shared captured text)
NoFilter attribute Any (shared captured text)
NoSort attribute Any (shared captured text)
NoSymLinks attribute Any (shared captured text)
PermissionMask attribute Any (shared captured text)
Readable attribute Any (shared captured text)
Reversed attribute Any (shared captured text)
Size attribute Any (shared captured text)
SortByMask attribute Any (shared captured text)
SortFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
SortFlags attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
System attribute Any (shared captured text)
Time attribute Any (shared captured text)
Type attribute Any (shared captured text)
TypeMask attribute Any (shared captured text)
Unsorted attribute Any (shared captured text)
Writable attribute Any (shared captured text)
__init__ function (self, *args: Any, **kwargs: Any) -> None Native constructor; consult class documentation for supported overloads. (shared captured text)
absoluteFilePath function (self, fileName: str) -> str X.absoluteFilePath(fileName) -> str (shared captured text)
absolutePath function (self) -> str X.absolutePath() -> str (shared captured text)
addSearchPath function (self, prefix: str, path: str) -> None X.addSearchPath(prefix, path) (shared captured text)
canonicalPath function (self) -> str X.canonicalPath() -> str (shared captured text)
cd function (self, dirName: str) -> bool X.cd(dirName) -> bool (shared captured text)
cdUp function (self) -> bool X.cdUp() -> bool (shared captured text)
className function (self, *args: Any, **kwargs: Any) -> Any Return the classname of the object (shared captured text)
cleanPath function (self, path: str) -> str X.cleanPath(path) -> str (shared captured text)
count function (self) -> int X.count() -> int (shared captured text)
current function (self) -> Any X.current() -> PythonQt.QtCore.QDir (shared captured text)
currentPath function (self) -> str X.currentPath() -> str (shared captured text)
delete function (self, *args: Any, **kwargs: Any) -> Any Deletes the C++ object (at your own risk, my friend!) (shared captured text)
dirName function (self) -> str X.dirName() -> str (shared captured text)
drives function (self) -> tuple X.drives() -> tuple (shared captured text)
entryInfoList function (self, nameFilters: Any, filters: Any, sort: Any) -> tuple X.entryInfoList(nameFilters, filters, sort) -> tuple (shared captured text)
entryList function (self, nameFilters: Any, filters: Any, sort: Any) -> tuple X.entryList(nameFilters, filters, sort) -> tuple (shared captured text)
exists function (self, name: Any) -> bool X.exists(name) -> bool (shared captured text)
filePath function (self, fileName: str) -> str X.filePath(fileName) -> str (shared captured text)
filter function (self) -> Any Returns the value set by [setFilter](https://doc.qt.io/archives/qt-5.15/qdir.html#setFilter)() (shared captured text)
fromNativeSeparators function (self, pathName: str) -> str X.fromNativeSeparators(pathName) -> str (shared captured text)
help function (self, *args: Any, **kwargs: Any) -> Any Shows the help of available methods for this class (shared captured text)
home function (self) -> Any X.home() -> PythonQt.QtCore.QDir (shared captured text)
homePath function (self) -> str X.homePath() -> str (shared captured text)
inherits function (self, *args: Any, **kwargs: Any) -> Any Returns if the class inherits or is of given type name (shared captured text)
isAbsolute function (self) -> bool X.isAbsolute() -> bool (shared captured text)
isAbsolutePath function (self, path: str) -> bool X.isAbsolutePath(path) -> bool (shared captured text)
isReadable function (self) -> bool X.isReadable() -> bool (shared captured text)
isRelative function (self) -> bool X.isRelative() -> bool (shared captured text)
isRelativePath function (self, path: str) -> bool X.isRelativePath(path) -> bool (shared captured text)
isRoot function (self) -> bool X.isRoot() -> bool (shared captured text)
listSeparator function (self) -> str Returns the native path list separator: ':' under Unix and ';' under Windows. (shared captured text)
makeAbsolute function (self) -> bool X.makeAbsolute() -> bool (shared captured text)
match function (self, filter: Any, fileName: str) -> bool X.match(filter, fileName) -> bool (shared captured text)
mkdir function (self, dirName: str) -> bool X.mkdir(dirName) -> bool (shared captured text)
mkpath function (self, dirPath: str) -> bool X.mkpath(dirPath) -> bool (shared captured text)
nameFilters function (self) -> tuple X.nameFilters() -> tuple (shared captured text)
nameFiltersFromString function (self, nameFilter: str) -> tuple X.nameFiltersFromString(nameFilter) -> tuple (shared captured text)
operator_subscript function (self, arg__1: Any) -> str X.operator_subscript(arg__1) -> str (shared captured text)
path function (self) -> str X.path() -> str (shared captured text)
refresh function (self) -> None Refreshes the directory information. (shared captured text)
relativeFilePath function (self, fileName: str) -> str X.relativeFilePath(fileName) -> str (shared captured text)
remove function (self, fileName: str) -> bool X.remove(fileName) -> bool (shared captured text)
removeRecursively function (self) -> bool X.removeRecursively() -> bool (shared captured text)
rename function (self, oldName: str, newName: str) -> bool X.rename(oldName, newName) -> bool (shared captured text)
rmdir function (self, dirName: str) -> bool X.rmdir(dirName) -> bool (shared captured text)
rmpath function (self, dirPath: str) -> bool X.rmpath(dirPath) -> bool (shared captured text)
root function (self) -> Any X.root() -> PythonQt.QtCore.QDir (shared captured text)
rootPath function (self) -> str X.rootPath() -> str (shared captured text)
searchPaths function (self, prefix: str) -> tuple X.searchPaths(prefix) -> tuple (shared captured text)
separator function (self) -> str Returns the native directory separator: "/" under Unix and "\" under Windows. (shared captured text)
setCurrent function (self, path: str) -> bool X.setCurrent(path) -> bool (shared captured text)
setFilter function (self, filter: Any) -> None Sets the filter used by [entryList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryList)() and [entryInfoList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryInfoList)() to filters. (shared captured text)
setNameFilters function (self, nameFilters: Any) -> None Sets the name filters used by [entryList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryList)() and [entryInfoList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryInfoList)() to the list of… (shared captured text)
setPath function (self, path: str) -> None Sets the path of the directory to path. (shared captured text)
setSearchPaths function (self, prefix: str, searchPaths: Any) -> None X.setSearchPaths(prefix, searchPaths) (shared captured text)
setSorting function (self, sort: Any) -> None Sets the sort order used by [entryList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryList)() and [entryInfoList](https://doc.qt.io/archives/qt-5.15/qdir.html#entryInfoList)(). (shared captured text)
sorting function (self) -> Any Returns the value set by [setSorting](https://doc.qt.io/archives/qt-5.15/qdir.html#setSorting)() (shared captured text)
swap function (self, other: Any) -> None Swaps this [QDir](https://doc.qt.io/archives/qt-5.15/qdir.html) instance with other. (shared captured text)
temp function (self) -> Any X.temp() -> PythonQt.QtCore.QDir (shared captured text)
tempPath function (self) -> str X.tempPath() -> str (shared captured text)
toNativeSeparators function (self, pathName: str) -> str X.toNativeSeparators(pathName) -> str (shared captured text)