Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QDir Class

TheQDir class provides access to directory structures and their contents.More...

Header:#include <QDir>

Note: All functions in this class arereentrant.

Public Types

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

Public Functions

QDir(const QDir & dir)
QDir(const QString & path = QString())
QDir(const QString & path, const QString & nameFilter, SortFlags sort = SortFlags( Name | IgnoreCase ), Filters filters = AllEntries)
~QDir()
QStringabsoluteFilePath(const QString & fileName) const
QStringabsolutePath() const
QStringcanonicalPath() const
boolcd(const QString & dirName)
boolcdUp()
uintcount() const
QStringdirName() const
QFileInfoListentryInfoList(const QStringList & nameFilters, Filters filters = NoFilter, SortFlags sort = NoSort) const
QFileInfoListentryInfoList(Filters filters = NoFilter, SortFlags sort = NoSort) const
QStringListentryList(const QStringList & nameFilters, Filters filters = NoFilter, SortFlags sort = NoSort) const
QStringListentryList(Filters filters = NoFilter, SortFlags sort = NoSort) const
boolexists(const QString & name) const
boolexists() const
QStringfilePath(const QString & fileName) const
Filtersfilter() const
boolisAbsolute() 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)
boolrename(const QString & oldName, const QString & newName)
boolrmdir(const QString & dirName) const
boolrmpath(const QString & dirPath) const
voidsetFilter(Filters filters)
voidsetNameFilters(const QStringList & nameFilters)
voidsetPath(const QString & path)
voidsetSorting(SortFlags sort)
SortFlagssorting() const
booloperator!=(const QDir & dir) const
QDir &operator=(const QDir & dir)
QDir &operator=(QDir && other)
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)
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)

Detailed Description

TheQDir class provides access to directory structures and their contents.

AQDir 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'sresource 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.

AQDir 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:/Documents and Settings")

On Windows, the second example above will be translated toC:\Documents and Settings when used to access files.

Examples of relative paths:

QDir("images/landscape.png")

You can use theisRelative() orisAbsolute() functions to check if aQDir is using a relative or an absolute file path. CallmakeAbsolute() to convert a relativeQDir to an absolute one.

Navigation and Directory Operations

A directory's path can be obtained with thepath() function, and a new path set with thesetPath() function. The absolute path to a directory is found by callingabsolutePath().

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

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

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

Directories can be created withmkdir(), renamed withrename(), and removed withrmdir().

You can test for the presence of a directory with a given name by usingexists(), and the properties of a directory can be tested withisReadable(),isAbsolute(),isRelative(), andisRoot().

Therefresh() 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 bycount(). A string list of the names of all the entries in a directory can be obtained withentryList(). If you need information about each entry, useentryInfoList() to obtain a list ofQFileInfo objects.

Paths to files and directories within a directory can be constructed usingfilePath() andabsoluteFilePath(). ThefilePath() function returns a path to the specified file or directory relative to the path of theQDir 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 theremove() function. Directories cannot be removed in the same way as files; usermdir() to remove them instead.

It is possible to reduce the number of entries returned byentryList() andentryInfoList() by applying filters to aQDir 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 tosetNameFilters(). Attribute filters consist of a bitwise OR combination of Filters, and these are specified when callingsetFilter(). The sort order is specified usingsetSorting() with a bitwise OR combination ofSortFlags.

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

Filter and sort order flags may also be specified when callingentryList() andentryInfoList() 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 returnQDir objects. There are also corresponding functions for these that return strings:

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

ThesetCurrent() 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, seeQCoreApplication::applicationDirPath().

Thedrives() 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 containC:/, and possibly other drive letters such asD:/, 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 thecanonicalPath() function.

Paths can also be simplified by usingcleanPath() 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 statictoNativeSeparators() 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 functionQFile::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;    }return0;}

See alsoQFileInfo,QFile,QFileDialog,QApplication::applicationDirPath(), andFind Files Example.

Member Type Documentation

enum QDir::Filter
flags QDir::Filters

This enum describes the filtering options available toQDir; e.g. forentryList() andentryInfoList(). 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::NoDotAndDotDot0x1000Do 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 constructedQDir will not filter out files based on their permissions, soentryList() andentryInfoList() 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 theReadable,Writable, andFiles flags allows all files to be listed for which the application has read access, write access or both. If theDirs andDrives 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 theentryInfoList() function to get the associatedQFileInfo objects and then use the QFileInfo::permissons() to obtain the permissions and ownership for each file.

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

typedef QDir::FilterSpec

UseQDir::Filters instead.

enum QDir::SortFlag
flags QDir::SortFlags

This enum describes the sort options available toQDir, e.g. forentryList() andentryInfoList(). 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 forQFlags<SortFlag>. It stores an OR combination of SortFlag values.

typedef QDir::SortSpec

UseQDir::SortFlags instead.

Member Function Documentation

QDir::QDir(constQDir & dir)

Constructs aQDir object that is a copy of theQDir object for directorydir.

See alsooperator=().

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

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

See alsocurrentPath().

QDir::QDir(constQString & path, constQString & nameFilter,SortFlags sort = SortFlags( Name | IgnoreCase ),Filters filters = AllEntries)

Constructs aQDir with pathpath, that filters its entries by name usingnameFilter and by attributes usingfilters. It also sorts the names usingsort.

The defaultnameFilter is an empty string, which excludes nothing; the defaultfilters isAllEntries, which also means exclude nothing. The defaultsort isName |IgnoreCase, i.e. sort by name case-insensitively.

Ifpath is an empty string,QDir uses "." (the current directory). IfnameFilter is an empty string,QDir uses the name filter "*" (all files).

Note thatpath need not exist.

See alsoexists(),setPath(),setNameFilter(),setFilter(), andsetSorting().

QDir::~QDir()

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

QString QDir::absoluteFilePath(constQString & fileName) const

Returns the absolute path name of a file in the directory. Doesnot check if the file actually exists in the directory; but seeexists(). Redundant multiple separators or "." and ".." directories infileName are not removed (seecleanPath()).

See alsorelativeFilePath(),filePath(), andcanonicalPath().

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 alsosetPath(),canonicalPath(),exists(),cleanPath(),dirName(), andabsoluteFilePath().

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

Addspath to the search path forprefix.

This function was introduced in Qt 4.3.

See alsosetSearchPaths().

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 thatabsolutePath() 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/binQDir 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 alsopath(),absolutePath(),exists(),cleanPath(),dirName(), andabsoluteFilePath().

bool QDir::cd(constQString & dirName)

Changes theQDir's directory todirName.

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

Calling cd("..") is equivalent to callingcdUp().

See alsocdUp(),isReadable(),exists(), andpath().

bool QDir::cdUp()

Changes directory by moving one directory up from theQDir's current directory.

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

See alsocd(),isReadable(),exists(), andpath().

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

Removes all multiple directory separators "/" and resolves any "."s or ".."s found in the path,path.

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 alsoabsolutePath() andcanonicalPath().

uint QDir::count() const

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

Equivalent toentryList().count().

See alsooperator[]() andentryList().

[static]QDir QDir::current()

Returns the application's current directory.

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

See alsocurrentPath(),setCurrent(),home(),root(), andtemp().

[static]QString QDir::currentPath()

Returns the absolute path of the application's current directory.

See alsocurrent(),setCurrent(),homePath(),rootPath(), andtempPath().

QString QDir::dirName() const

Returns the name of the directory; this isnot 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 seeexists().

See alsopath(),filePath(),absolutePath(), andabsoluteFilePath().

[static]QFileInfoList QDir::drives()

Returns a list of the root directories on this system.

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

See alsoroot() androotPath().

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

Returns a list ofQFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set withsetNameFilters() andsetFilter(), and sorted according to the flags set withsetSorting().

The name filter, file attribute filter, and sorting specification can be overridden using thenameFilters,filters, andsort arguments.

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

See alsoentryList(),setNameFilters(),setSorting(),setFilter(),isReadable(), andexists().

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

This is an overloaded function.

Returns a list ofQFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set withsetNameFilters() andsetFilter(), and sorted according to the flags set withsetSorting().

The attribute filter and sorting specifications can be overridden using thefilters andsort arguments.

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

See alsoentryList(),setNameFilters(),setSorting(),setFilter(),isReadable(), andexists().

QStringList QDir::entryList(constQStringList & nameFilters,Filters filters = NoFilter,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 withsetNameFilters() andsetFilter(), and sorted according to the flags set withsetSorting().

The name filter, file attribute filter, and sorting specification can be overridden using thenameFilters,filters, andsort arguments.

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

See alsoentryInfoList(),setNameFilters(),setSorting(), andsetFilter().

QStringList QDir::entryList(Filters filters = NoFilter,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 withsetNameFilters() andsetFilter(), and sorted according to the flags set withsetSorting().

The attribute filter and sorting specifications can be overridden using thefilters andsort 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 alsoentryInfoList(),setNameFilters(),setSorting(), andsetFilter().

bool QDir::exists(constQString & name) const

Returns true if the file calledname exists; otherwise returns false.

Unlessname 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 alsoQFileInfo::exists() andQFile::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 alsoQFileInfo::exists() andQFile::exists().

QString QDir::filePath(constQString & fileName) const

Returns the path name of a file in the directory. Doesnot check if the file actually exists in the directory; but seeexists(). If theQDir is relative the returned path name will also be relative. Redundant multiple separators or "." and ".." directories infileName are not removed (seecleanPath()).

See alsodirName(),absoluteFilePath(),isRelative(), andcanonicalPath().

Filters QDir::filter() const

Returns the value set bysetFilter()

See alsosetFilter().

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

ReturnspathName 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 alsotoNativeSeparators() andseparator().

[static]QDir QDir::home()

Returns the user's home directory.

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

SeehomePath() for details.

See alsodrives(),current(),root(), andtemp().

[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 thetoNativeSeparators() 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 theUSERPROFILE environment variable.
  2. The path formed by concatenating theHOMEDRIVE andHOMEPATH environment variables.
  3. The path specified by theHOME environment variable.
  4. The path returned by therootPath() function (which uses theSystemDrive environment variable)
  5. TheC:/ directory.

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

On Symbian this typically returns "c:/data", i.e. the same as native PathInfo::PhoneMemoryRootPath().

See alsohome(),currentPath(),rootPath(), andtempPath().

bool QDir::isAbsolute() const

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

See alsoisRelative(),makeAbsolute(), andcleanPath().

[static]bool QDir::isAbsolutePath(constQString & path)

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

See alsoisAbsolute(),isRelativePath(),makeAbsolute(), andcleanPath().

bool QDir::isReadable() const

Returns true if the directory is readableand 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 alsoQFileInfo::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 alsomakeAbsolute(),isAbsolute(),isAbsolutePath(), andcleanPath().

[static]bool QDir::isRelativePath(constQString & path)

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

See alsoisRelative(),isAbsolutePath(), andmakeAbsolute().

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 usecanonicalPath(), e.g.

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

See alsoroot() androotPath().

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 alsoisAbsolute(),isAbsolutePath(),isRelative(), andcleanPath().

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

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

See alsoQRegExp wildcard matching,QRegExp::exactMatch(),entryList(), andentryInfoList().

[static]bool QDir::match(constQStringList & filters, constQString & fileName)

This is an overloaded function.

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

See alsoQRegExp wildcard matching,QRegExp::exactMatch(),entryList(), andentryInfoList().

bool QDir::mkdir(constQString & dirName) const

Creates a sub-directory calleddirName.

Returns true on success; otherwise returns false.

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

See alsormdir().

bool QDir::mkpath(constQString & dirPath) const

Creates the directory pathdirPath.

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 alsormpath().

QStringList QDir::nameFilters() const

Returns the string list set bysetNameFilters()

See alsosetNameFilters().

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 (seesetPath()).

See alsosetPath(),absolutePath(),exists(),cleanPath(),dirName(),absoluteFilePath(),toNativeSeparators(), andmakeAbsolute().

void QDir::refresh() const

Refreshes the directory information.

QString QDir::relativeFilePath(constQString & fileName) const

Returns the path tofileName 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 alsoabsoluteFilePath(),filePath(), andcanonicalPath().

bool QDir::remove(constQString & fileName)

Removes the file,fileName.

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

bool QDir::rename(constQString & oldName, constQString & newName)

Renames a file or directory fromoldName tonewName, and returns true if successful; otherwise returns false.

On most file systems, rename() fails only ifoldName does not exist, ifnewName andoldName are not on the same partition 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 ifnewName points to an open file.

bool QDir::rmdir(constQString & dirName) const

Removes the directory specified bydirName.

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

Returns true if successful; otherwise returns false.

See alsomkdir().

bool QDir::rmpath(constQString & dirPath) const

Removes the directory pathdirPath.

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

Returns true if successful; otherwise returns false.

See alsomkpath().

[static]QDir QDir::root()

Returns the root directory.

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

SeerootPath() for details.

See alsodrives(),current(),home(), andtemp().

[static]QString QDir::rootPath()

Returns the absolute path of the root directory.

For Unix operating systems this returns "/". For Windows and Symbian file systems this normally returns "c:/". I.E. the root of the system drive.

See alsoroot(),drives(),currentPath(),homePath(), andtempPath().

[static]QStringList QDir::searchPaths(constQString & prefix)

Returns the search paths forprefix.

This function was introduced in Qt 4.3.

See alsosetSearchPaths() andaddSearchPath().

[static]QChar QDir::separator()

Returns the native directory separator: "/" under Unix (including Mac OS X) 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 usetoNativeSeparators().

[static]bool QDir::setCurrent(constQString & path)

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

See alsocurrent(),currentPath(),home(),root(), andtemp().

void QDir::setFilter(Filters filters)

Sets the filter used byentryList() andentryInfoList() tofilters. The filter is used to specify the kind of files that should be returned byentryList() andentryInfoList(). SeeQDir::Filter.

See alsofilter() andsetNameFilters().

void QDir::setNameFilters(constQStringList & nameFilters)

Sets the name filters used byentryList() andentryInfoList() to the list of filters specified bynameFilters.

Each name filter is a wildcard (globbing) filter that understands* and? wildcards. (SeeQRegExp wildcard matching.)

For example, the following code sets three name filters on aQDir 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 alsonameFilters() andsetFilter().

void QDir::setPath(constQString & path)

Sets the path of the directory topath. 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 usingexists().

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 alsopath(),absolutePath(),exists(),cleanPath(),dirName(),absoluteFilePath(),isRelative(), andmakeAbsolute().

[static]void QDir::setSearchPaths(constQString & prefix, constQStringList & searchPaths)

Sets or replaces Qt's search paths for file names with the prefixprefix tosearchPaths.

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 toThe Qt Resource System.

This function was introduced in Qt 4.3.

See alsosearchPaths().

void QDir::setSorting(SortFlags sort)

Sets the sort order used byentryList() andentryInfoList().

Thesort is specified by OR-ing values from the enumQDir::SortFlag.

See alsosorting() andSortFlag.

SortFlags QDir::sorting() const

Returns the value set bysetSorting()

See alsosetSorting() andSortFlag.

[static]QDir QDir::temp()

Returns the system's temporary directory.

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

SeetempPath() for details.

See alsodrives(),current(),home(), androot().

[static]QString QDir::tempPath()

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

On Unix/Linux systems this is the path in theTMPDIR environment variable or/tmp ifTMPDIR is not defined. On Windows this is usually the path in theTEMP orTMP environment variable. Whether a directory separator is added to the end or not, depends on the operating system.

See alsotemp(),currentPath(),homePath(), androotPath().

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

ReturnspathName 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 alsofromNativeSeparators() andseparator().

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

Returns true if directorydir 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");

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

Makes a copy of thedir object and assigns it to thisQDir object.

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

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

Returns true if directorydir 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 positionpos in the list of file names. Equivalent toentryList().at(index).pos must be a valid index position in the list (i.e., 0 <= pos <count()).

See alsocount() andentryList().

Macro Documentation

voidQ_CLEANUP_RESOURCE( name)

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

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 theQ_INIT_RESOURCE documentation for a workaround.

Example:

Q_CLEANUP_RESOURCE(myapp);

This function was introduced in Qt 4.1.

See alsoQ_INIT_RESOURCE() andThe Qt Resource System.

voidQ_INIT_RESOURCE( name)

Initializes the resources specified by the.qrc file with the specified basename. Normally, Qt 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 calledmyapp.qrc, you can ensure that the resources are initialized at startup by adding this line to yourmain() 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 resourcemyapp from the functionMyNamespace::myFunction:

inlinevoid initMyResource() { Q_INIT_RESOURCE(myapp); }namespace MyNamespace{...void myFunction()    {        initMyResource();    }}

See alsoQ_CLEANUP_RESOURCE() andThe Qt Resource System.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp