QDir类

QDir Class

The QDir class provides access to directory structures and their contents. More...

Header:#include <QDir>
qmake:QT += core

Note: All functions in this class are reentrant.

Public Types

enumFilter { Dirs, AllDirs, Files, Drives, ..., CaseSensitive }
flagsFilters
enumSortFlag { Name, Time, Size, Type, ..., LocaleAware }
flagsSortFlags

Public Functions

 QDir(const QString &path, const QString &nameFilter, QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries)
 QDir(const QString &path = QString())
 QDir(const QDir &dir)
QDir &operator=(QDir &&other)
QDir &operator=(const QDir &dir)
 ~QDir()
QStringabsoluteFilePath(const QString &fileName) const
QStringabsolutePath() const
QStringcanonicalPath() const
boolcd(const QString &dirName)
boolcdUp()
uintcount() const
QStringdirName() const
QFileInfoListentryInfoList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const
QFileInfoListentryInfoList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const
QStringListentryList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const
QStringListentryList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const
boolexists(const QString &name) const
boolexists() const
QStringfilePath(const QString &fileName) const
QDir::Filtersfilter() const
boolisAbsolute() const
boolisEmpty(QDir::Filters filters = Filters(AllEntries | NoDotAndDotDot)) const
boolisReadable() const
boolisRelative() const
boolisRoot() const
boolmakeAbsolute()
boolmkdir(const QString &dirName) const
boolmkpath(const QString &dirPath) const
QStringListnameFilters() const
QStringpath() const
voidrefresh() const
QStringrelativeFilePath(const QString &fileName) const
boolremove(const QString &fileName)
boolremoveRecursively()
boolrename(const QString &oldName, const QString &newName)
boolrmdir(const QString &dirName) const
boolrmpath(const QString &dirPath) const
voidsetFilter(QDir::Filters filters)
voidsetNameFilters(const QStringList &nameFilters)
voidsetPath(const QString &path)
voidsetSorting(QDir::SortFlags sort)
QDir::SortFlagssorting() const
voidswap(QDir &other)
booloperator!=(const QDir &dir) const
booloperator==(const QDir &dir) const
QStringoperator[](int pos) const

Static Public Members

voidaddSearchPath(const QString &prefix, const QString &path)
QStringcleanPath(const QString &path)
QDircurrent()
QStringcurrentPath()
QFileInfoListdrives()
QStringfromNativeSeparators(const QString &pathName)
QDirhome()
QStringhomePath()
boolisAbsolutePath(const QString &path)
boolisRelativePath(const QString &path)
QCharlistSeparator()
boolmatch(const QString &filter, const QString &fileName)
boolmatch(const QStringList &filters, const QString &fileName)
QDirroot()
QStringrootPath()
QStringListsearchPaths(const QString &prefix)
QCharseparator()
boolsetCurrent(const QString &path)
voidsetSearchPaths(const QString &prefix, const QStringList &searchPaths)
QDirtemp()
QStringtempPath()
QStringtoNativeSeparators(const QString &pathName)

Macros

voidQ_CLEANUP_RESOURCE(name)
voidQ_INIT_RESOURCE(name)

详细说明

的QDir用来操作路径名称,关于路径和文件的访问信息和操作底层文件系统。它也可以用来访问Qt的资源系统

Qt使用“ /”作为通用目录分隔符,就像使用“ /”作为URL中的路径分隔符一样。如果您始终使用“ /”作为目录分隔符,则Qt将转换您的路径以符合基础操作系统。

的QDir可以指向使用相对或绝对路径的文件。绝对路径以目录分隔符(在Windows下可选地以驱动器规范开头)开头。相对文件名以目录名或文件名开头,并指定相对于当前目录的路径。

绝对路径的示例:

QDir("/home/user/Documents")
QDir("C:/Documents and Settings")

在Windows上,上面的第二个示例C:\Documents and Settings在用于访问文件时将转换为。

相对路径的示例:

QDir("images/landscape.png")

您可以使用isRelative()或isAbsolute()函数来检查QDir是使用相对还是绝对文件路径。调用makeAbsolute()将相对的QDir转换为绝对的QDir

导航和目录操作

可以使用path()函数获取目录的路径,并使用setPath()函数获取新路径。目录的绝对路径可通过调用absolutePath()找到。

使用dirName()函数可以找到目录的名称。这通常会返回绝对路径中的最后一个元素,该元素指定目录的位置。但是,它也可以返回“。” 如果QDir代表当前目录。

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

目录的路径也可以使用cd()和cdUp()函数进行更改,这两个函数的作用类似于熟悉的Shell命令。当使用现有目录的名称调用cd()时,QDir对象将更改目录,使其代替该目录。所述CDUP()函数改变的目录的QDir对象,以便它是指它的父目录; 即cd(“ ..”)等效于cdUp()。

可以使用mkdir()创建目录,使用rename()重命名目录,并使用rmdir()删除目录。

可以通过使用测试目录的存在下与一个给定的名称存在(),和一个目录的属性可以与被测试isReadable(),isAbsolute(),而isRelative(),和isRoot()。

刷新()函数从磁盘重新读取目录中的数据。

文件和目录内容

目录包含许多条目,代表文件,目录和符号链接。目录中的条目数由count()返回。可以使用entryList()获得目录中所有条目名称的字符串列表。如果需要有关每个条目的信息,请使用entryInfoList()获得QFileInfo对象的列表。

可以使用filePath()和absoluteFilePath()构造目录中文件和目录的路径。的文件路径()函数返回到指定的文件或目录相对于所述的路径的路径的QDir对象; absoluteFilePath()返回指定文件或目录的绝对路径。这些功能都不检查文件或目录的存在。他们只构造路径。

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

可以使用remove()函数删除文件。目录不能以与文件相同的方式删除;使用rmdir()删除它们。

通过将过滤器应用于QDir对象,可以减少由entryList()和entryInfoList()返回的条目数。您可以应用名称过滤器来指定带有文件名需要匹配的通配符的模式,用于选择条目属性并可以区分文件和目录的属性过滤器以及排序顺序。

名称过滤器是传递给setNameFilters()的字符串列表。属性过滤器由过滤器的按位或组合组成,这些在调用setFilter()时指定。排序顺序指定使用setSorting()具有一个按位或组合SortFlags

您可以使用match()函数测试文件名是否与过滤器匹配

当调用entryList()和entryInfoList()时,也可以指定过滤器和排序顺序标志,以覆盖先前定义的行为。

当前目录和其他特殊路径

提供了一些返回QDir对象的静态函数来访问某些公共目录。这些还具有返回字符串的相应函数:

QDirQStringReturn 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

的setCurrent()静态函数也可用于设置应用程序的工作目录。

如果要查找包含应用程序可执行文件的目录,请参见QCoreApplication :: applicationDirPath()。

所述驱动器()静态函数提供根目录的列表对包含文件系统的每个设备。在Unix系统上,这将返回一个包含单个根目录“ /”的列表。在Windows上,取决于用户系统的配置,该列表通常将包含C:/,并可能包含其他驱动器号,例如D:/

路径操作和字符串

包含“。”的路径 使用路径canonicalPath()将引用当前目录的元素,引用父目录的“ ..”元素和符号链接简化为规范形式。

也可以通过使用cleanPath()删除多余的“ /”和“ ..”元素来简化路径。

有时需要能够以本机表示形式显示用户平台的路径。静态的toNativeSeparators()函数返回指定路径的副本,在该副本中,每个目录分隔符都被基础操作系统的适当分隔符替换。

例子

检查目录是否存在:

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")); // "/tmp/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;
}

See also QFileInfoQFileQFileDialogQCoreApplication::applicationDirPath(), and Find Files Example.

Member Type Documentation

enum QDir::Filter
flags QDir::Filters

This enum describes the filtering options available to QDir; e.g. for entryList() and entryInfoList(). The filter value is specified by combining values from the following list using the bitwise OR operator:

ConstantValueDescription
QDir::Dirs0x001List directories that match the filters.
QDir::AllDirs0x400List all directories; i.e. don't apply the filters to directory names.
QDir::Files0x002List files.
QDir::Drives0x004List disk drives (ignored under Unix).
QDir::NoSymLinks0x008Do not list symbolic links (ignored by operating systems that don't support symbolic links).
QDir::NoDotAndDotDotNoDot | NoDotDotDo not list the special entries "." and "..".
QDir::NoDot0x2000Do not list the special entry ".".
QDir::NoDotDot0x4000Do not list the special entry "..".
QDir::AllEntriesDirs | Files | DrivesList directories, files, drives and symlinks (this does not list broken symlinks unless you specify System).
QDir::Readable0x010List files for which the application has read access. The Readable value needs to be combined with Dirs or Files.
QDir::Writable0x020List files for which the application has write access. The Writable value needs to be combined with Dirs or Files.
QDir::Executable0x040List files for which the application has execute access. The Executable value needs to be combined with Dirs or Files.
QDir::Modified0x080Only list files that have been modified (ignored on Unix).
QDir::Hidden0x100List hidden files (on Unix, files starting with a ".").
QDir::System0x200List system files (on Unix, FIFOs, sockets and device files are included; on Windows, .lnk files are included)
QDir::CaseSensitive0x800The filter should be case sensitive.

Functions that use Filter enum values to filter lists of files and directories will include symbolic links to files and directories unless you set the NoSymLinks value.

A default constructed QDir will not filter out files based on their permissions, so entryList() and entryInfoList() will return all files that are readable, writable, executable, or any combination of the three. This makes the default easy to write, and at the same time useful.

For example, setting the ReadableWritable, and Files flags allows all files to be listed for which the application has read access, write access or both. If the Dirs and Drives flags are also included in this combination then all drives, directories, all files that the application can read, write, or execute, and symlinks to such files/directories can be listed.

To retrieve the permissons for a directory, use the entryInfoList() function to get the associated QFileInfo objects and then use the QFileInfo::permissons() to obtain the permissions and ownership for each file.

The Filters type is a typedef for QFlags<Filter>. It stores an OR combination of Filter values.

enum QDir::SortFlag
flags QDir::SortFlags

This enum describes the sort options available to QDir, e.g. for entryList() and entryInfoList(). The sort value is specified by OR-ing together values from the following list:

ConstantValueDescription
QDir::Name0x00Sort by name.
QDir::Time0x01Sort by time (modification time).
QDir::Size0x02Sort by file size.
QDir::Type0x80Sort by file type (extension).
QDir::Unsorted0x03Do not sort.
QDir::NoSort-1Not sorted by default.
QDir::DirsFirst0x04Put the directories first, then the files.
QDir::DirsLast0x20Put the files first, then the directories.
QDir::Reversed0x08Reverse the sort order.
QDir::IgnoreCase0x10Sort case-insensitively.
QDir::LocaleAware0x40Sort items appropriately using the current locale settings.

You can only specify one of the first four.

If you specify both DirsFirst and Reversed, directories are still put first, but in reverse order; the files will be listed after the directories, again in reverse order.

The SortFlags type is a typedef for QFlags<SortFlag>. It stores an OR combination of SortFlag values.

Member Function Documentation

QDir::QDir(const QString &path, const QString &nameFilterQDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries)

Constructs a QDir with path path, that filters its entries by name using nameFilter and by attributes using filters. It also sorts the names using sort.

The default nameFilter is an empty string, which excludes nothing; the default filters is AllEntries, which also means exclude nothing. The default sort is Name | IgnoreCase, i.e. sort by name case-insensitively.

If path is an empty string, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files).

Note that path need not exist.

See also exists(), setPath(), setNameFilters(), setFilter(), and setSorting().

QDir::QDir(const QString &path = QString())

Constructs a QDir pointing to the given directory path. If path is empty the program's working directory, ("."), is used.

See also currentPath().

QDir::QDir(const QDir &dir)

Constructs a QDir object that is a copy of the QDir object for directory dir.

See also operator=().

QDir &QDir::operator=(QDir &&other)

Move-assigns other to this QDir instance.

This function was introduced in Qt 5.2.

QDir &QDir::operator=(const QDir &dir)

Makes a copy of the dir object and assigns it to this QDir object.

QDir::~QDir()

Destroys the QDir object frees up its resources. This has no effect on the underlying directory in the file system.

QString QDir::absoluteFilePath(const QString &fileName) const

Returns the absolute path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()).

See also relativeFilePath(), filePath(), and canonicalPath().

QString QDir::absolutePath() const

Returns the absolute path (a path that starts with "/" or with a drive specification), which may contain symbolic links, but never contains redundant ".", ".." or multiple separators.

See also setPath(), canonicalPath(), exists(), cleanPath(), dirName(), and absoluteFilePath().

[static]void QDir::addSearchPath(const QString &prefix, const QString &path)

Adds path to the search path for prefix.

This function was introduced in Qt 4.3.

See also setSearchPaths().

QString QDir::canonicalPath() const

Returns the canonical path, i.e. a path without symbolic links or redundant "." or ".." elements.

On systems that do not have symbolic links this function will always return the same string that absolutePath() returns. If the canonical path does not exist (normally due to dangling symbolic links) canonicalPath() returns an empty string.

Example:

QString bin = "/local/bin";         // where /local/bin is a symlink to /usr/bin
QDir binDir(bin);
QString canonicalBin = binDir.canonicalPath();
// canonicalBin now equals "/usr/bin"

QString ls = "/local/bin/ls";       // where ls is the executable "ls"
QDir lsDir(ls);
QString canonicalLs = lsDir.canonicalPath();
// canonicalLS now equals "/usr/bin/ls".

See also path(), absolutePath(), exists(), cleanPath(), dirName(), and absoluteFilePath().

bool QDir::cd(const QString &dirName)

Changes the QDir's directory to dirName.

Returns true if the new directory exists; otherwise returns false. Note that the logical cd() operation is not performed if the new directory does not exist.

Calling cd("..") is equivalent to calling cdUp().

See also cdUp(), isReadable(), exists(), and path().

bool QDir::cdUp()

Changes directory by moving one directory up from the QDir's current directory.

Returns true if the new directory exists; otherwise returns false. Note that the logical cdUp() operation is not performed if the new directory does not exist.

See also cd(), isReadable(), exists(), and path().

[static]QString QDir::cleanPath(const QString &path)

Returns path with directory separators normalized (converted to "/") and redundant ones removed, and "."s and ".."s resolved (as far as possible).

Symbolic links are kept. This function does not return the canonical path, but rather the simplest version of the input. For example, "./local" becomes "local", "local/../bin" becomes "bin" and "/local/usr/../bin" becomes "/local/bin".

See also absolutePath() and canonicalPath().

uint QDir::count() const

Returns the total number of directories and files in the directory.

Equivalent to entryList().count().

See also operator[]() and entryList().

[static]QDir QDir::current()

Returns the application's current directory.

The directory is constructed using the absolute path of the current directory, ensuring that its path() will be the same as its absolutePath().

See also currentPath(), setCurrent(), home(), root(), and temp().

[static]QString QDir::currentPath()

Returns the absolute path of the application's current directory. The current directory is the last directory set with QDir::setCurrent() or, if that was never called, the directory at which this application was started at by the parent process.

See also current(), setCurrent(), homePath(), rootPath(), tempPath(), and QCoreApplication::applicationDirPath().

QString QDir::dirName() const

Returns the name of the directory; this is not the same as the path, e.g. a directory with the name "mail", might have the path "/var/spool/mail". If the directory has no name (e.g. it is the root directory) an empty string is returned.

No check is made to ensure that a directory with this name actually exists; but see exists().

See also path(), filePath(), absolutePath(), and absoluteFilePath().

[static]QFileInfoList QDir::drives()

Returns a list of the root directories on this system.

On Windows this returns a list of QFileInfo objects containing "C:/", "D:/", etc. On other operating systems, it returns a list containing just one root directory (i.e. "/").

See also root() and rootPath().

QFileInfoList QDir::entryInfoList(const QStringList &nameFiltersQDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const

Returns a list of QFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().

The name filter, file attribute filter, and sorting specification can be overridden using the nameFiltersfilters, and sort arguments.

Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.

See also entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), and exists().

QFileInfoList QDir::entryInfoList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const

This is an overloaded function.

Returns a list of QFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().

The attribute filter and sorting specifications can be overridden using the filters and sort arguments.

Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.

See also entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), and exists().

QStringList QDir::entryList(const QStringList &nameFiltersQDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const

Returns a list of the names of all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().

The name filter, file attribute filter, and sorting specification can be overridden using the nameFiltersfilters, and sort arguments.

Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.

See also entryInfoList(), setNameFilters(), setSorting(), and setFilter().

QStringList QDir::entryList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const

This is an overloaded function.

Returns a list of the names of all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().

The attribute filter and sorting specifications can be overridden using the filters and sort arguments.

Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.

Note: To list symlinks that point to non existing files, System must be passed to the filter.

See also entryInfoList(), setNameFilters(), setSorting(), and setFilter().

bool QDir::exists(const QString &name) const

Returns true if the file called name exists; otherwise returns false.

Unless name contains an absolute file path, the file name is assumed to be relative to the directory itself, so this function is typically used to check for the presence of files within a directory.

See also QFileInfo::exists() and QFile::exists().

bool QDir::exists() const

This is an overloaded function.

Returns true if the directory exists; otherwise returns false. (If a file with the same name is found this function will return false).

The overload of this function that accepts an argument is used to test for the presence of files and directories within a directory.

See also QFileInfo::exists() and QFile::exists().

QString QDir::filePath(const QString &fileName) const

Returns the path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). If the QDir is relative the returned path name will also be relative. Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()).

See also dirName(), absoluteFilePath(), isRelative(), and canonicalPath().

QDir::Filters QDir::filter() const

Returns the value set by setFilter()

See also setFilter().

[static]QString QDir::fromNativeSeparators(const QString &pathName)

Returns pathName using '/' as file separator. On Windows, for instance, fromNativeSeparators("c:\\winnt\\system32") returns "c:/winnt/system32".

The returned string may be the same as the argument on some operating systems, for example on Unix.

This function was introduced in Qt 4.2.

See also toNativeSeparators() and separator().

[static]QDir QDir::home()

Returns the user's home directory.

The directory is constructed using the absolute path of the home directory, ensuring that its path() will be the same as its absolutePath().

See homePath() for details.

See also drives(), current(), root(), and temp().

[static]QString QDir::homePath()

Returns the absolute path of the user's home directory.

Under Windows this function will return the directory of the current user's profile. Typically, this is:

C:/Documents and Settings/Username

Use the toNativeSeparators() function to convert the separators to the ones that are appropriate for the underlying operating system.

If the directory of the current user's profile does not exist or cannot be retrieved, the following alternatives will be checked (in the given order) until an existing and available path is found:

  1. The path specified by the USERPROFILE environment variable.
  2. The path formed by concatenating the HOMEDRIVE and HOMEPATH environment variables.
  3. The path specified by the HOME environment variable.
  4. The path returned by the rootPath() function (which uses the SystemDrive environment variable)
  5. The C:/ directory.

Under non-Windows operating systems the HOME environment variable is used if it exists, otherwise the path returned by the rootPath().

See also home(), currentPath(), rootPath(), and tempPath().

bool QDir::isAbsolute() const

Returns true if the directory's path is absolute; otherwise returns false. See isAbsolutePath().

See also isRelative(), makeAbsolute(), and cleanPath().

[static]bool QDir::isAbsolutePath(const QString &path)

Returns true if path is absolute; returns false if it is relative.

See also isAbsolute(), isRelativePath(), makeAbsolute(), and cleanPath().

bool QDir::isEmpty(QDir::Filters filters = Filters(AllEntries | NoDotAndDotDot)) const

Returns whether the directory is empty.

Equivalent to count() == 0 with filters QDir::AllEntries | QDir::NoDotAndDotDot, but faster as it just checks whether the directory contains at least one entry.

Note: Unless you set the filters flags to include QDir::NoDotAndDotDot (as the default value does), no directory is empty.

This function was introduced in Qt 5.9.

See also count(), entryList(), and setFilter().

bool QDir::isReadable() const

Returns true if the directory is readable and we can open files by name; otherwise returns false.

Warning: A false value from this function is not a guarantee that files in the directory are not accessible.

See also QFileInfo::isReadable().

bool QDir::isRelative() const

Returns true if the directory path is relative; otherwise returns false. (Under Unix a path is relative if it does not start with a "/").

See also makeAbsolute(), isAbsolute(), isAbsolutePath(), and cleanPath().

[static]bool QDir::isRelativePath(const QString &path)

Returns true if path is relative; returns false if it is absolute.

See also isRelative(), isAbsolutePath(), and makeAbsolute().

bool QDir::isRoot() const

Returns true if the directory is the root directory; otherwise returns false.

Note: If the directory is a symbolic link to the root directory this function returns false. If you want to test for this use canonicalPath(), e.g.

QDir dir("/tmp/root_link");
dir = dir.canonicalPath();
if (dir.isRoot())
    qWarning("It is a root link");

See also root() and rootPath().

[static]QChar QDir::listSeparator()

Returns the native path list separator: ':' under Unix and ';' under Windows.

This function was introduced in Qt 5.6.

See also separator().

bool QDir::makeAbsolute()

Converts the directory path to an absolute path. If it is already absolute nothing happens. Returns true if the conversion succeeded; otherwise returns false.

See also isAbsolute(), isAbsolutePath(), isRelative(), and cleanPath().

[static]bool QDir::match(const QString &filter, const QString &fileName)

Returns true if the fileName matches the wildcard (glob) pattern filter; otherwise returns false. The filter may contain multiple patterns separated by spaces or semicolons. The matching is case insensitive.

See also QRegularExpression Wildcard MatchingentryList(), and entryInfoList().

[static]bool QDir::match(const QStringList &filters, const QString &fileName)

This is an overloaded function.

Returns true if the fileName matches any of the wildcard (glob) patterns in the list of filters; otherwise returns false. The matching is case insensitive.

See also QRegularExpression Wildcard MatchingentryList(), and entryInfoList().

bool QDir::mkdir(const QString &dirName) const

Creates a sub-directory called dirName.

Returns true on success; otherwise returns false.

If the directory already exists when this function is called, it will return false.

See also rmdir().

bool QDir::mkpath(const QString &dirPath) const

Creates the directory path dirPath.

The function will create all parent directories necessary to create the directory.

Returns true if successful; otherwise returns false.

If the path already exists when this function is called, it will return true.

See also rmpath().

QStringList QDir::nameFilters() const

Returns the string list set by setNameFilters()

See also setNameFilters().

QString QDir::path() const

Returns the path. This may contain symbolic links, but never contains redundant ".", ".." or multiple separators.

The returned path can be either absolute or relative (see setPath()).

See also setPath(), absolutePath(), exists(), cleanPath(), dirName(), absoluteFilePath(), toNativeSeparators(), and makeAbsolute().

void QDir::refresh() const

Refreshes the directory information.

QString QDir::relativeFilePath(const QString &fileName) const

Returns the path to fileName relative to the directory.

QDir dir("/home/bob");
QString s;

s = dir.relativeFilePath("images/file.jpg");     // s is "images/file.jpg"
s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt"

See also absoluteFilePath(), filePath(), and canonicalPath().

bool QDir::remove(const QString &fileName)

Removes the file, fileName.

Returns true if the file is removed successfully; otherwise returns false.

bool QDir::removeRecursively()

Removes the directory, including all its contents.

Returns true if successful, otherwise false.

If a file or directory cannot be removed, removeRecursively() keeps going and attempts to delete as many files and sub-directories as possible, then returns false.

If the directory was already removed, the method returns true (expected result already reached).

Note: this function is meant for removing a small application-internal directory (such as a temporary directory), but not user-visible directories. For user-visible operations, it is rather recommended to report errors more precisely to the user, to offer solutions in case of errors, to show progress during the deletion since it could take several minutes, etc.

This function was introduced in Qt 5.0.

bool QDir::rename(const QString &oldName, const QString &newName)

Renames a file or directory from oldName to newName, and returns true if successful; otherwise returns false.

On most file systems, rename() fails only if oldName does not exist, or if a file with the new name already exists. However, there are also other reasons why rename() can fail. For example, on at least one file system rename() fails if newName points to an open file.

If oldName is a file (not a directory) that can't be renamed right away, Qt will try to copy oldName to newName and remove oldName.

See also QFile::rename().

bool QDir::rmdir(const QString &dirName) const

Removes the directory specified by dirName.

The directory must be empty for rmdir() to succeed.

Returns true if successful; otherwise returns false.

See also mkdir().

bool QDir::rmpath(const QString &dirPath) const

Removes the directory path dirPath.

The function will remove all parent directories in dirPath, provided that they are empty. This is the opposite of mkpath(dirPath).

Returns true if successful; otherwise returns false.

See also mkpath().

[static]QDir QDir::root()

Returns the root directory.

The directory is constructed using the absolute path of the root directory, ensuring that its path() will be the same as its absolutePath().

See rootPath() for details.

See also drives(), current(), home(), and temp().

[static]QString QDir::rootPath()

Returns the absolute path of the root directory.

For Unix operating systems this returns "/". For Windows file systems this normally returns "c:/".

See also root(), drives(), currentPath(), homePath(), and tempPath().

[static]QStringList QDir::searchPaths(const QString &prefix)

Returns the search paths for prefix.

This function was introduced in Qt 4.3.

See also setSearchPaths() and addSearchPath().

[static]QChar QDir::separator()

Returns the native directory separator: "/" under Unix and "\" under Windows.

You do not need to use this function to build file paths. If you always use "/", Qt will translate your paths to conform to the underlying operating system. If you want to display paths to the user using their operating system's separator use toNativeSeparators().

See also listSeparator().

[static]bool QDir::setCurrent(const QString &path)

Sets the application's current working directory to path. Returns true if the directory was successfully changed; otherwise returns false.

See also current(), currentPath(), home(), root(), and temp().

void QDir::setFilter(QDir::Filters filters)

Sets the filter used by entryList() and entryInfoList() to filters. The filter is used to specify the kind of files that should be returned by entryList() and entryInfoList(). See QDir::Filter.

See also filter() and setNameFilters().

void QDir::setNameFilters(const QStringList &nameFilters)

Sets the name filters used by entryList() and entryInfoList() to the list of filters specified by nameFilters.

Each name filter is a wildcard (globbing) filter that understands * and ? wildcards. See QRegularExpression Wildcard Matching.

For example, the following code sets three name filters on a QDir to ensure that only files with extensions typically used for C++ source files are listed:

    QStringList filters;
    filters << "*.cpp" << "*.cxx" << "*.cc";
    dir.setNameFilters(filters);

See also nameFilters() and setFilter().

void QDir::setPath(const QString &path)

Sets the path of the directory to path. The path is cleaned of redundant ".", ".." and of multiple separators. No check is made to see whether a directory with this path actually exists; but you can check for yourself using exists().

The path can be either absolute or relative. 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. An example of an absolute path is the string "/tmp/quartz", a relative path might look like "src/fatlib".

See also path(), absolutePath(), exists(), cleanPath(), dirName(), absoluteFilePath(), isRelative(), and makeAbsolute().

[static]void QDir::setSearchPaths(const QString &prefix, const QStringList &searchPaths)

Sets or replaces Qt's search paths for file names with the prefix prefix to searchPaths.

To specify a prefix for a file name, prepend the prefix followed by a single colon (e.g., "images:undo.png", "xmldocs:books.xml"). prefix can only contain letters or numbers (e.g., it cannot contain a colon, nor a slash).

Qt uses this search path to locate files with a known prefix. The search path entries are tested in order, starting with the first entry.

QDir::setSearchPaths("icons", QStringList(QDir::homePath() + "/images"));
QDir::setSearchPaths("docs", QStringList(":/embeddedDocuments"));
...
QPixmap pixmap("icons:undo.png"); // will look for undo.png in QDir::homePath() + "/images"
QFile file("docs:design.odf"); // will look in the :/embeddedDocuments resource path

File name prefix must be at least 2 characters long to avoid conflicts with Windows drive letters.

Search paths may contain paths to The Qt Resource System.

This function was introduced in Qt 4.3.

See also searchPaths().

void QDir::setSorting(QDir::SortFlags sort)

Sets the sort order used by entryList() and entryInfoList().

The sort is specified by OR-ing values from the enum QDir::SortFlag.

See also sorting() and SortFlag.

QDir::SortFlags QDir::sorting() const

Returns the value set by setSorting()

See also setSorting() and SortFlag.

void QDir::swap(QDir &other)

Swaps this QDir instance with other. This function is very fast and never fails.

This function was introduced in Qt 5.0.

[static]QDir QDir::temp()

Returns the system's temporary directory.

The directory is constructed using the absolute canonical path of the temporary directory, ensuring that its path() will be the same as its absolutePath().

See tempPath() for details.

See also drives(), current(), home(), and root().

[static]QString QDir::tempPath()

Returns the absolute canonical path of the system's temporary directory.

On Unix/Linux systems this is the path in the TMPDIR environment variable or /tmp if TMPDIR is not defined. On Windows this is usually the path in the TEMP or TMP environment variable. The path returned by this method doesn't end with a directory separator unless it is the root directory (of a drive).

See also temp(), currentPath(), homePath(), and rootPath().

[static]QString QDir::toNativeSeparators(const QString &pathName)

Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system.

On Windows, toNativeSeparators("c:/winnt/system32") returns "c:\winnt\system32".

The returned string may be the same as the argument on some operating systems, for example on Unix.

This function was introduced in Qt 4.2.

See also fromNativeSeparators() and separator().

bool QDir::operator!=(const QDir &dir) const

Returns true if directory dir and this directory have different paths or different sort or filter settings; otherwise returns false.

Example:

// The current directory is "/usr/local"
QDir d1("/usr/local/bin");
d1.setFilter(QDir::Executable);
QDir d2("bin");
if (d1 != d2)
    qDebug("They differ");

bool QDir::operator==(const QDir &dir) const

Returns true if directory dir and this directory have the same path and their sort and filter settings are the same; otherwise returns false.

Example:

// The current directory is "/usr/local"
QDir d1("/usr/local/bin");
QDir d2("bin");
if (d1 == d2)
    qDebug("They're the same");

QString QDir::operator[](int pos) const

Returns the file name at position pos in the list of file names. Equivalent to entryList().at(index). pos must be a valid index position in the list (i.e., 0 <= pos < count()).

See also count() and entryList().

Macro Documentation

void Q_CLEANUP_RESOURCE(name)

Unloads the resources specified by the .qrc file with the base name name.

Normally, Qt resources are unloaded automatically when the application terminates, but if the resources are located in a plugin that is being unloaded, call Q_CLEANUP_RESOURCE() to force removal of your resources.

Note: This macro cannot be used in a namespace. Please see the Q_INIT_RESOURCE documentation for a workaround.

Example:

Q_CLEANUP_RESOURCE(myapp);

This function was introduced in Qt 4.1.

See also Q_INIT_RESOURCE() and The Qt Resource System.

void Q_INIT_RESOURCE(name)

Initializes the resources specified by the .qrc file with the specified base name. Normally, when resources are built as part of the application, the resources are loaded automatically at startup. The Q_INIT_RESOURCE() macro is necessary on some platforms for resources stored in a static library.

For example, if your application's resources are listed in a file called myapp.qrc, you can ensure that the resources are initialized at startup by adding this line to your main() function:

Q_INIT_RESOURCE(myapp);

If the file name contains characters that cannot be part of a valid C++ function name (such as '-'), they have to be replaced by the underscore character ('_').

Note: This macro cannot be used in a namespace. It should be called from main(). If that is not possible, the following workaround can be used to init the resource myapp from the function MyNamespace::myFunction:

inline void initMyResource() { Q_INIT_RESOURCE(myapp); }

namespace MyNamespace
{
    ...

    void myFunction()
    {
        initMyResource();
    }
}

See also Q_CLEANUP_RESOURCE() and The Qt Resource System.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值