Skip to content

PythonQt.QtCore.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
AllDirs attribute Any
AllEntries attribute Any
CaseSensitive attribute Any
Dirs attribute Any
DirsFirst attribute Any
DirsLast attribute Any
Drives attribute Any
Executable attribute Any
Files attribute Any
Filter attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
Filters attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
Hidden attribute Any
IgnoreCase attribute Any
LocaleAware attribute Any
Modified attribute Any
Name attribute Any
NoDot attribute Any
NoDotAndDotDot attribute Any
NoDotDot attribute Any
NoFilter attribute Any
NoSort attribute Any
NoSymLinks attribute Any
PermissionMask attribute Any
Readable attribute Any
Reversed attribute Any
Size attribute Any
SortByMask attribute Any
SortFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
SortFlags attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
System attribute Any
Time attribute Any
Type attribute Any
TypeMask attribute Any
Unsorted attribute Any
Writable attribute Any
__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
absolutePath function (self) -> str X.absolutePath() -> str
addSearchPath function (self, prefix: str, path: str) -> None X.addSearchPath(prefix, path)
canonicalPath function (self) -> str X.canonicalPath() -> str
cd function (self, dirName: str) -> bool X.cd(dirName) -> bool
cdUp function (self) -> bool X.cdUp() -> bool
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
count function (self) -> int X.count() -> int
current function (self) -> Any X.current() -> PythonQt.QtCore.QDir
currentPath function (self) -> str X.currentPath() -> str
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
drives function (self) -> tuple X.drives() -> tuple
entryInfoList function (self, nameFilters: Any, filters: Any, sort: Any) -> tuple X.entryInfoList(nameFilters, filters, sort) -> tuple
entryList function (self, nameFilters: Any, filters: Any, sort: Any) -> tuple X.entryList(nameFilters, filters, sort) -> tuple
exists function (self, name: Any) -> bool X.exists(name) -> bool
filePath function (self, fileName: str) -> str X.filePath(fileName) -> str
filter function (self) -> Any Returns the value set by [setFilter](https://doc.qt.io/archives/qt-5.15/qdir.html#setFilter)()
fromNativeSeparators function (self, pathName: str) -> str X.fromNativeSeparators(pathName) -> str
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
homePath function (self) -> str X.homePath() -> str
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
isAbsolutePath function (self, path: str) -> bool X.isAbsolutePath(path) -> bool
isReadable function (self) -> bool X.isReadable() -> bool
isRelative function (self) -> bool X.isRelative() -> bool
isRelativePath function (self, path: str) -> bool X.isRelativePath(path) -> bool
isRoot function (self) -> bool X.isRoot() -> bool
listSeparator function (self) -> str Returns the native path list separator: ':' under Unix and ';' under Windows.
makeAbsolute function (self) -> bool X.makeAbsolute() -> bool
match function (self, filter: Any, fileName: str) -> bool X.match(filter, fileName) -> bool
mkdir function (self, dirName: str) -> bool X.mkdir(dirName) -> bool
mkpath function (self, dirPath: str) -> bool X.mkpath(dirPath) -> bool
nameFilters function (self) -> tuple X.nameFilters() -> tuple
nameFiltersFromString function (self, nameFilter: str) -> tuple X.nameFiltersFromString(nameFilter) -> tuple
operator_subscript function (self, arg__1: Any) -> str X.operator_subscript(arg__1) -> str
path function (self) -> str X.path() -> str
refresh function (self) -> None Refreshes the directory information.
relativeFilePath function (self, fileName: str) -> str X.relativeFilePath(fileName) -> str
remove function (self, fileName: str) -> bool X.remove(fileName) -> bool
removeRecursively function (self) -> bool X.removeRecursively() -> bool
rename function (self, oldName: str, newName: str) -> bool X.rename(oldName, newName) -> bool
rmdir function (self, dirName: str) -> bool X.rmdir(dirName) -> bool
rmpath function (self, dirPath: str) -> bool X.rmpath(dirPath) -> bool
root function (self) -> Any X.root() -> PythonQt.QtCore.QDir
rootPath function (self) -> str X.rootPath() -> str
searchPaths function (self, prefix: str) -> tuple X.searchPaths(prefix) -> tuple
separator function (self) -> str Returns the native directory separator: "/" under Unix and "\" under Windows.
setCurrent function (self, path: str) -> bool X.setCurrent(path) -> bool
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.
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…
setPath function (self, path: str) -> None Sets the path of the directory to path.
setSearchPaths function (self, prefix: str, searchPaths: Any) -> None X.setSearchPaths(prefix, searchPaths)
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)().
sorting function (self) -> Any Returns the value set by [setSorting](https://doc.qt.io/archives/qt-5.15/qdir.html#setSorting)()
swap function (self, other: Any) -> None Swaps this [QDir](https://doc.qt.io/archives/qt-5.15/qdir.html) instance with other.
temp function (self) -> Any X.temp() -> PythonQt.QtCore.QDir
tempPath function (self) -> str X.tempPath() -> str
toNativeSeparators function (self, pathName: str) -> str X.toNativeSeparators(pathName) -> str