The QDir class provides access to directory structures and their contents. 更多...
头: | #include <QDir> |
CMake: |
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
注意: 此类的所有函数 可重入 .
enum | Filter { Dirs, AllDirs, Files, Drives, NoSymLinks, …, CaseSensitive } |
flags | 过滤器 |
enum | SortFlag { Name, Time, Size, Type, Unsorted, …, LocaleAware } |
flags | SortFlags |
QDir (const QString & path = QString()) | |
QDir (const QString & path , const QString & nameFilter , QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries) | |
QDir (const std::filesystem::path & path ) | |
QDir (const std::filesystem::path & path , const QString & nameFilter , QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries) | |
QDir (const QDir & dir ) | |
~QDir () | |
QString | absoluteFilePath (const QString & fileName ) const |
QString | absolutePath () const |
QString | canonicalPath () const |
bool | cd (const QString & dirName ) |
bool | cdUp () |
qsizetype | count () const |
QString | dirName () const |
QFileInfoList | entryInfoList (const QStringList & nameFilters , QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const |
QFileInfoList | entryInfoList (QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const |
QStringList | entryList (const QStringList & nameFilters , QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const |
QStringList | entryList (QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const |
bool | exists (const QString & name ) const |
bool | exists () const |
QString | filePath (const QString & fileName ) const |
std::filesystem::path | filesystemAbsolutePath () const |
std::filesystem::path | filesystemCanonicalPath () const |
std::filesystem::path | filesystemPath () const |
QDir::Filters | filter () const |
bool | isAbsolute () const |
bool | isEmpty (QDir::Filters filters = Filters(AllEntries | NoDotAndDotDot)) const |
bool | isReadable () const |
bool | isRelative () const |
bool | isRoot () const |
bool | makeAbsolute () |
bool | mkdir (const QString & dirName , QFile::Permissions permissions ) const |
bool | mkdir (const QString & dirName ) const |
bool | mkpath (const QString & dirPath ) const |
QStringList | nameFilters () const |
QString | path () const |
void | refresh () const |
QString | relativeFilePath (const QString & fileName ) const |
bool | remove (const QString & fileName ) |
bool | removeRecursively () |
bool | rename (const QString & oldName , const QString & newName ) |
bool | rmdir (const QString & dirName ) const |
bool | rmpath (const QString & dirPath ) const |
void | setFilter (QDir::Filters filters ) |
void | setNameFilters (const QStringList & nameFilters ) |
void | setPath (const QString & path ) |
void | setPath (const std::filesystem::path & path ) |
void | setSorting (QDir::SortFlags sort ) |
QDir::SortFlags | sorting () const |
void | swap (QDir & other ) |
bool | operator!= (const QDir & dir ) const |
QDir & | operator= (const QDir & dir ) |
QDir & | operator= (QDir && other ) |
bool | operator== (const QDir & dir ) const |
QString | operator[] (qsizetype pos ) const |
void | addSearchPath (const QString & prefix , const QString & path ) |
void | addSearchPath (const QString & prefix , const std::filesystem::path & path ) |
QString | cleanPath (const QString & path ) |
QDir | current () |
QString | currentPath () |
QFileInfoList | drives () |
QString | fromNativeSeparators (const QString & pathName ) |
QDir | home () |
QString | homePath () |
bool | isAbsolutePath (const QString & path ) |
bool | isRelativePath (const QString & path ) |
QChar | listSeparator () |
bool | match (const QString & filter , const QString & fileName ) |
bool | match (const QStringList & filters , const QString & fileName ) |
QDir | root () |
QString | rootPath () |
QStringList | searchPaths (const QString & prefix ) |
QChar | separator () |
bool | setCurrent (const QString & path ) |
void | setSearchPaths (const QString & prefix , const QStringList & searchPaths ) |
QDir | temp () |
QString | tempPath () |
QString | toNativeSeparators (const QString & pathName ) |
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 资源系统 .
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")
可以使用 isRelative () 或 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.
注意: Paths starting with a colon ( : ) are always considered absolute, as they denote a QResource .
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 () 和 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 (),和 isRoot ().
The refresh () function re-reads the directory's data from disk.
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 对象。
Paths to files and directories within a directory can be constructed using filePath () 和 absoluteFilePath ()。 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 () 和 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 () 函数。
Filter and sort order flags may also be specified when calling entryList () 和 entryInfoList () in order to override previously defined behavior.
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.
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 () 函数。
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.
Check if a directory exists:
QDir dir("example"); if (!dir.exists()) qWarning("Cannot find the example directory");
(We could also use one of the static convenience functions QFileInfo::exists () 或 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; }
在 Android,会应用一些局限性当处理 内容 URI (统一资源标识符) :
另请参阅 QFileInfo , QFile , QFileDialog , QCoreApplication::applicationDirPath (),和 抓取更多范例 .
This enum describes the filtering options available to QDir ; e.g. for entryList () 和 entryInfoList (). The filter value is specified by combining values from the following list using the bitwise OR operator:
常量 | 值 | 描述 |
---|---|---|
QDir::Dirs
|
0x001
|
List directories that match the filters. |
QDir::AllDirs
|
0x400
|
List all directories; i.e. don't apply the filters to directory names. |
QDir::Files
|
0x002
|
List files. |
QDir::Drives
|
0x004
|
List disk drives (ignored under Unix). |
QDir::NoSymLinks
|
0x008
|
Do not list symbolic links (ignored by operating systems that don't support symbolic links). |
QDir::NoDotAndDotDot
|
NoDot | NoDotDot
|
Do not list the special entries "." and "..". |
QDir::NoDot
|
0x2000
|
Do not list the special entry ".". |
QDir::NoDotDot
|
0x4000
|
Do not list the special entry "..". |
QDir::AllEntries
|
Dirs | Files | Drives
|
List directories, files, drives and symlinks (this does not list broken symlinks unless you specify System). |
QDir::Readable
|
0x010
|
List files for which the application has read access. The Readable value needs to be combined with Dirs or Files. |
QDir::Writable
|
0x020
|
List files for which the application has write access. The Writable value needs to be combined with Dirs or Files. |
QDir::Executable
|
0x040
|
List files for which the application has execute access. The Executable value needs to be combined with Dirs or Files. |
QDir::Modified
|
0x080
|
Only list files that have been modified (ignored on Unix). |
QDir::Hidden
|
0x100
|
List hidden files (on Unix, files starting with a "."). |
QDir::System
|
0x200
|
List system files (on Unix, FIFOs, sockets and device files are included; on Windows,
.lnk
files are included)
|
QDir::CaseSensitive
|
0x800
|
The 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 () 和 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
Readable
,
可写
,和
文件
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 permissions for a directory, use the entryInfoList () function to get the associated QFileInfo objects and then use the QFileInfo::permissions () 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.
This enum describes the sort options available to QDir , e.g. for entryList () 和 entryInfoList (). The sort value is specified by OR-ing together values from the following list:
常量 | 值 | 描述 |
---|---|---|
QDir::Name
|
0x00
|
Sort by name. |
QDir::Time
|
0x01
|
Sort by time (modification time). |
QDir::Size
|
0x02
|
Sort by file size. |
QDir::Type
|
0x80
|
Sort by file type (extension). |
QDir::Unsorted
|
0x03
|
Do not sort. |
QDir::NoSort
|
-1
|
Not sorted by default. |
QDir::DirsFirst
|
0x04
|
Put the directories first, then the files. |
QDir::DirsLast
|
0x20
|
Put the files first, then the directories. |
QDir::Reversed
|
0x08
|
Reverse the sort order. |
QDir::IgnoreCase
|
0x10
|
Sort case-insensitively. |
QDir::LocaleAware
|
0x40
|
Sort 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.
Constructs a QDir pointing to the given directory path . If path is empty the program's working directory, ("."), is used.
另请参阅 currentPath ().
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 .
默认 nameFilter is an empty string, which excludes nothing; the default filters is AllEntries , which also excludes nothing. The default sort is 名称 | IgnoreCase , i.e. sort by name case-insensitively.
若 path is an empty string, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files).
注意: path need not exist.
另请参阅 exists (), setPath (), setNameFilters (), setFilter (),和 setSorting ().
[since 6.0]
QDir::
QDir
(const
std::filesystem::path
&
path
)
Constructs a QDir pointing to the given directory path . If path is empty the program's working directory, ("."), is used.
该函数在 Qt 6.0 引入。
另请参阅 currentPath ().
[since 6.0]
QDir::
QDir
(const
std::filesystem::path
&
path
, const
QString
&
nameFilter
,
QDir::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 .
默认 nameFilter is an empty string, which excludes nothing; the default filters is AllEntries , which also excludes nothing. The default sort is 名称 | IgnoreCase , i.e. sort by name case-insensitively.
若 path is empty, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files).
注意: path need not exist.
该函数在 Qt 6.0 引入。
另请参阅 exists (), setPath (), setNameFilters (), setFilter (),和 setSorting ().
Constructs a QDir object that is a copy of the QDir object for directory dir .
另请参阅 operator= ().
销毁 QDir object frees up its resources. This has no effect on the underlying directory in the file system.
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 ()).
另请参阅 relativeFilePath (), filePath (),和 canonicalPath ().
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.
另请参阅 setPath (), canonicalPath (), exists (), cleanPath (), dirName (),和 absoluteFilePath ().
[static]
void
QDir::
addSearchPath
(const
QString
&
prefix
, const
QString
&
path
)
添加 path to the search path for prefix .
另请参阅 setSearchPaths ().
[static, since 6.0]
void
QDir::
addSearchPath
(const
QString
&
prefix
, const
std::filesystem::path
&
path
)
这是重载函数。
该函数在 Qt 6.0 引入。
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.
范例:
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".
另请参阅 path (), absolutePath (), exists (), cleanPath (), dirName (),和 absoluteFilePath ().
改变 QDir 的目录为 dirName .
返回
true
若新目录存在;否则返回
false
。注意:逻辑 cd() 操作不履行若新目录不存在。
调用 cd("..") 相当于调用 cdUp ().
另请参阅 cdUp (), isReadable (), exists (),和 path ().
通过上移一目录来改变目录从 QDir 的当前目录。
返回
true
若新目录存在;否则返回
false
。注意:逻辑 cdUp() 操作不履行若新目录不存在。
注意: On Android, this is not supported for content URIs. For more information, see DocumentFile.getParentFile() .
另请参阅 cd (), isReadable (), exists (),和 path ().
[static]
QString
QDir::
cleanPath
(const
QString
&
path
)
返回 path with directory separators normalized (that is, platform-native separators 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".
另请参阅 absolutePath () 和 canonicalPath ().
Returns the total number of directories and files in the directory.
相当于 entryList ().count().
注意:
In Qt versions prior to 6.5, this function returned
uint
, not
qsizetype
.
另请参阅 operator[] () 和 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 ().
另请参阅 currentPath (), setCurrent (), home (), root (),和 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.
另请参阅 current (), setCurrent (), homePath (), rootPath (), tempPath (),和 QCoreApplication::applicationDirPath ().
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 ().
另请参阅 path (), filePath (), absolutePath (),和 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. This does not return drives with ejectable media that are empty. On other operating systems, it returns a list containing just one root directory (i.e. "/").
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 () 和 setFilter (), and sorted according to the flags set with setSorting ().
The name filter, file attribute filter, and sorting specification can be overridden using the nameFilters , filters ,和 sort 自变量。
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
另请参阅 entryList (), setNameFilters (), setSorting (), setFilter (), isReadable (),和 exists ().
这是重载函数。
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 () 和 setFilter (), and sorted according to the flags set with setSorting ().
The attribute filter and sorting specifications can be overridden using the filters and sort 自变量。
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
另请参阅 entryList (), setNameFilters (), setSorting (), setFilter (), isReadable (),和 exists ().
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 () 和 setFilter (), and sorted according to the flags set with setSorting ().
The name filter, file attribute filter, and sorting specification can be overridden using the nameFilters , filters ,和 sort 自变量。
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
另请参阅 entryInfoList (), setNameFilters (), setSorting (),和 setFilter ().
这是重载函数。
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 () 和 setFilter (), and sorted according to the flags set with setSorting ().
The attribute filter and sorting specifications can be overridden using the filters and sort 自变量。
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
注意: To list symlinks that point to non existing files, 系统 must be passed to the filter.
另请参阅 entryInfoList (), setNameFilters (), setSorting (),和 setFilter ().
返回
true
if the file called
name
exists; otherwise returns false.
除非 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.
另请参阅 QFileInfo::exists () 和 QFile::exists ().
这是重载函数。
返回
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.
另请参阅 QFileInfo::exists () 和 QFile::exists ().
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 ()).
另请参阅 dirName (), absoluteFilePath (), isRelative (),和 canonicalPath ().
[since 6.0]
std::filesystem::path
QDir::
filesystemAbsolutePath
() const
返回
absolutePath
() 作为
std::filesystem::path
.
该函数在 Qt 6.0 引入。
另请参阅 absolutePath ().
[since 6.0]
std::filesystem::path
QDir::
filesystemCanonicalPath
() const
返回
canonicalPath
() 作为
std::filesystem::path
.
该函数在 Qt 6.0 引入。
另请参阅 canonicalPath ().
[since 6.0]
std::filesystem::path
QDir::
filesystemPath
() const
返回
path
() 作为
std::filesystem::path
.
该函数在 Qt 6.0 引入。
另请参阅 path ().
Returns the value set by setFilter ()
另请参阅 setFilter ().
[static]
QString
QDir::
fromNativeSeparators
(const
QString
&
pathName
)
返回
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.
另请参阅 toNativeSeparators () 和 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 ().
见 homePath () 了解细节。
另请参阅 drives (), current (), root (),和 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:/Users/Username
使用 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:
USERPROFILE
环境变量。
HOMEDRIVE
and
HOMEPATH
environment variables.
HOME
环境变量。
SystemDrive
environment variable)
C:/
目录。
Under non-Windows operating systems the
HOME
environment variable is used if it exists, otherwise the path returned by the
rootPath
().
另请参阅 home (), currentPath (), rootPath (),和 tempPath ().
返回
true
if the directory's path is absolute; otherwise returns
false
。见
isAbsolutePath
().
注意: Paths starting with a colon ( : ) are always considered absolute, as they denote a QResource .
另请参阅 isRelative (), makeAbsolute (),和 cleanPath ().
[static]
bool
QDir::
isAbsolutePath
(const
QString
&
path
)
返回
true
if
path
is absolute; returns
false
if it is relative.
注意: Paths starting with a colon ( : ) are always considered absolute, as they denote a QResource .
另请参阅 isAbsolute (), isRelativePath (), makeAbsolute (), cleanPath (),和 QResource .
Returns whether the directory is empty.
相当于
count() == 0
with filters
QDir::AllEntries | QDir::NoDotAndDotDot
, but faster as it just checks whether the directory contains at least one entry.
注意:
Unless you set the
filters
flags to include
QDir::NoDotAndDotDot
(as the default value does), no directory is empty.
另请参阅 count (), entryList (),和 setFilter ().
返回
true
if the directory is readable
and
we can open files by name; otherwise returns
false
.
警告: A false value from this function is not a guarantee that files in the directory are not accessible.
另请参阅 QFileInfo::isReadable ().
返回
true
if the directory path is relative; otherwise returns false. (Under Unix a path is relative if it does not start with a "/").
注意: Paths starting with a colon ( : ) are always considered absolute, as they denote a QResource .
另请参阅 makeAbsolute (), isAbsolute (), isAbsolutePath (),和 cleanPath ().
[static]
bool
QDir::
isRelativePath
(const
QString
&
path
)
返回
true
if
path
is relative; returns
false
if it is absolute.
注意: Paths starting with a colon ( : ) are always considered absolute, as they denote a QResource .
另请参阅 isRelative (), isAbsolutePath (),和 makeAbsolute ().
返回
true
if the directory is the root directory; otherwise returns
false
.
注意:
If the directory is a symbolic link to the root directory this function returns
false
. If you want to test for this use
canonicalPath
(),如
QDir dir("/tmp/root_link"); dir = dir.canonicalPath(); if (dir.isRoot()) qWarning("It is a root link");
[static constexpr]
QChar
QDir::
listSeparator
()
Returns the native path list separator: ':' under Unix and ';' under Windows.
另请参阅 separator ().
Converts the directory path to an absolute path. If it is already absolute nothing happens. Returns
true
if the conversion succeeded; otherwise returns
false
.
另请参阅 isAbsolute (), isAbsolutePath (), isRelative (),和 cleanPath ().
[static]
bool
QDir::
match
(const
QString
&
filter
, const
QString
&
fileName
)
返回
true
若
fileName
matches the wildcard (glob) pattern
filter
;否则返回
false
。
filter
may contain multiple patterns separated by spaces or semicolons. The matching is case insensitive.
另请参阅 QRegularExpression::fromWildcard (), entryList (),和 entryInfoList ().
[static]
bool
QDir::
match
(const
QStringList
&
filters
, const
QString
&
fileName
)
这是重载函数。
返回
true
若
fileName
matches any of the wildcard (glob) patterns in the list of
filters
;否则返回
false
. The matching is case insensitive.
另请参阅 QRegularExpression::fromWildcard (), entryList (),和 entryInfoList ().
[since 6.3]
bool
QDir::
mkdir
(const
QString
&
dirName
,
QFile::Permissions
permissions
) const
Creates a sub-directory called dirName .
返回
true
当成功时;否则返回
false
.
If the directory already exists when this function is called, it will return
false
.
The permissions of the created directory are set to permissions .
On POSIX systems the permissions are influenced by the value of
umask
.
在 Windows,是使用 ACL (访问控制列表) 模拟权限。这些 ACL (访问控制列表) 可以是非规范次序,当授予组的权限比其它组少时。具有这种权限的文件和目录将生成警告,当打开 Properties 对话框的 Security 选项卡时。向组授予授予其它组的所有权限,能避免这种警告。
该函数在 Qt 6.3 引入。
另请参阅 rmdir ().
这是重载函数。
Creates a sub-directory called dirName with default permissions.
On POSIX systems the default is to grant all permissions allowed by
umask
. On Windows, the new directory inherits its permissions from its parent directory.
Creates the directory path dirPath .
The function will create all parent directories necessary to create the directory.
返回
true
若成功;否则返回
false
.
If the path already exists when this function is called, it will return true.
另请参阅 rmpath ().
Returns the string list set by setNameFilters ()
另请参阅 setNameFilters ().
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 ()).
另请参阅 setPath (), absolutePath (), exists (), cleanPath (), dirName (), absoluteFilePath (), toNativeSeparators (),和 makeAbsolute ().
Refreshes the directory information.
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"
另请参阅 absoluteFilePath (), filePath (),和 canonicalPath ().
Removes the file, fileName .
返回
true
if the file is removed successfully; otherwise returns
false
.
Removes the directory, including all its contents.
返回
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).
注意: 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.
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.
若 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 .
另请参阅 QFile::rename ().
Removes the directory specified by dirName .
The directory must be empty for rmdir() to succeed.
返回
true
若成功;否则返回
false
.
另请参阅 mkdir ().
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).
返回
true
若成功;否则返回
false
.
另请参阅 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 ().
见 rootPath () 了解细节。
另请参阅 drives (), current (), home (),和 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:/".
另请参阅 root (), drives (), currentPath (), homePath (),和 tempPath ().
[static]
QStringList
QDir::
searchPaths
(const
QString
&
prefix
)
Returns the search paths for prefix .
另请参阅 setSearchPaths () 和 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 ().
另请参阅 listSeparator ().
[static]
bool
QDir::
setCurrent
(const
QString
&
path
)
Sets the application's current working directory to
path
。返回
true
if the directory was successfully changed; otherwise returns
false
.
QString absolute = "/local/bin"; QString relative = "local/bin"; QFileInfo absFile(absolute); QFileInfo relFile(relative); QDir::setCurrent(QDir::rootPath()); // absFile and relFile now point to the same file QDir::setCurrent("/tmp"); // absFile now points to "/local/bin", // while relFile points to "/tmp/local/bin"
另请参阅 current (), currentPath (), home (), root (),和 temp ().
Sets the filter used by entryList () 和 entryInfoList () 到 filters . The filter is used to specify the kind of files that should be returned by entryList () 和 entryInfoList ()。见 QDir::Filter .
另请参阅 filter () 和 setNameFilters ().
Sets the name filters used by entryList () 和 entryInfoList () to the list of filters specified by nameFilters .
Each name filter is a wildcard (globbing) filter that understands
*
and
?
wildcards. See
QRegularExpression::fromWildcard
().
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);
另请参阅 nameFilters () 和 setFilter ().
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".
另请参阅 path (), absolutePath (), exists (), cleanPath (), dirName (), absoluteFilePath (), isRelative (),和 makeAbsolute ().
[since 6.0]
void
QDir::
setPath
(const
std::filesystem::path
&
path
)
这是重载函数。
该函数在 Qt 6.0 引入。
[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 Qt 资源系统 .
另请参阅 searchPaths ().
Sets the sort order used by entryList () 和 entryInfoList ().
The sort is specified by OR-ing values from the enum QDir::SortFlag .
Returns the value set by setSorting ()
另请参阅 setSorting () 和 SortFlag .
交换此 QDir 实例与 other 。此函数非常快且从不失败。
[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 ().
见 tempPath () 了解细节。
另请参阅 drives (), current (), home (),和 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).
另请参阅 temp (), currentPath (), homePath (),和 rootPath ().
[static]
QString
QDir::
toNativeSeparators
(const
QString
&
pathName
)
返回 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.
另请参阅 fromNativeSeparators () 和 separator ().
返回
true
if directory
dir
and this directory have different paths or different sort or filter settings; otherwise returns false.
范例:
// The current directory is "/usr/local" QDir d1("/usr/local/bin"); d1.setFilter(QDir::Executable); QDir d2("bin"); if (d1 != d2) qDebug("They differ");
Makes a copy of the dir object and assigns it to this QDir 对象。
移动赋值 other 到此 QDir 实例。
返回
true
if directory
dir
and this directory have the same path and their sort and filter settings are the same; otherwise returns
false
.
范例:
// The current directory is "/usr/local" QDir d1("/usr/local/bin"); QDir d2("bin"); if (d1 == d2) qDebug("They're the same");
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 ()).
注意:
In Qt versions prior to 6.5,
pos
was an
int
, not
qsizetype
.