SoFunction
Updated on 2025-04-06

Qt QDir path class and usage method

QDir Detailed explanation

Preface

File and directory operations are common tasks in software development, such as traversing folders, checking whether files exist, creating folders, etc. Qt provides a powerful class—QDir, specifically used to operate directories in file systems.QDirEncapsulates multiple platform-independent file system operation methods, allowing developers to easily process files and directories in cross-platform projects.

This article will introduceQDirThe purpose of this is to list commonly used constructors and member functions, and combine code examples to help developers fully grasp theQDirHow to use it.

What is QDir?

QDiris a class of Qt, specifically used to operate directories in file systems. It provides a series of methods to manage and query directories, such as setting up the current directory, enumerating files and subdirectories in the directory, creating and deleting directories, etc.QDirMaking complex file system operations simple and efficient, while ensuring cross-platform compatibility.

QDirThe operation is based on a string path and can accept absolute or relative paths. In addition, it supports filters and sorting functions, allowing for flexible filtering and arrangement of content in a directory.

QDir constructor and common member functions

Constructor

1. Default constructor

Function prototype

QDir();

effect
Create a representative of the current working directoryQDirObject.

Sample code

QDir dir;
qDebug() << "Current directory:" << ();

2. Specify the constructor of the path

Function prototype

QDir(const QString &path);

effect
Create a path that represents the specified pathQDirObject.

parameter

path: The directory path to represent.

Sample code

QDir dir("/home/user/documents");
qDebug() << "Directory path:" << ();

Common member functions

1. exists

Function prototype

bool exists() const;
bool exists(const QString &name) const;

effect
Checks whether the directory or specified file exists.

parameter

(No parameters) Check whether the current directory exists.name: The name of the file or subdirectory, check whether it exists.

Return value
If it exists, returntrue; otherwise returnfalse

Sample code

QDir dir("/home/user/documents");
if (()) {
    qDebug() << "Directory exists.";
}
if (("")) {
    qDebug() << "File exists in the directory.";
}

2. mkpath

Function prototype

bool mkpath(const QString &path) const;

effect
Creates all parent directories of the specified path (create the directory recursively).

parameter

path: The path to create.

Return value
If the directory is successfully created, returntrue; otherwise returnfalse

Sample code

QDir dir;
if (("/home/user/new_folder/sub_folder")) {
    qDebug() << "Directories created successfully.";
}

3. rmpath

Function prototype

bool rmpath(const QString &path) const;

effect
Delete an empty directory of the specified path.

parameter

path: The path to delete.

Return value
If the directory is successfully deleted, returntrue; otherwise returnfalse

Sample code

QDir dir;
if (("/home/user/new_folder/sub_folder")) {
    qDebug() << "Directory removed successfully.";
}

4. setPath

Function prototype

void setPath(const QString &path);

effect
set upQDirThe path represented by the object.

parameter

path: The path to set.

Sample code

QDir dir;
("/home/user/documents");
qDebug() << "Directory path set to:" << ();

5. entryList

Function prototype

QStringList entryList(const QStringList &nameFilters = QStringList(),
                      Filters filters = NoFilter,
                      SortFlags sort = NoSort) const;

effect
Get a list of files and subdirectories in the directory that meet the criteria.

parameter

  • nameFilters: File name filter (e.g.*.txt)。
  • filters: Filter options (e.g.QDir::Files, QDir::Dirswait).
  • sort: Sort options (such asQDir::Name, QDir::Timewait).

Return value
Returns a list of strings containing the file and subdirectory names that match the criteria.

Sample code

QDir dir("/home/user/documents");
QStringList filters;
filters << "*.txt" << "*.docx";
QStringList files = (filters, QDir::Files);
qDebug() << "Text and doc files:" << files;

6. rename

Function prototype

bool rename(const QString &oldName, const QString &newName);

effect
Rename a file or subdirectory.

parameter

  • oldName: The name of the old file or directory.
  • newName: The name of the new file or directory.

Return value
If renamed successfully, returntrue; otherwise returnfalse

Sample code

QDir dir("/home/user/documents");
if (("old_file.txt", "new_file.txt")) {
    qDebug() << "File renamed successfully.";
}

7. absolutePathandabsoluteFilePath

Function prototype

QString absolutePath() const;
QString absoluteFilePath(const QString &fileName) const;

effect
Gets the absolute path to the current directory or the absolute path to the file.

parameter

  • fileName: The name of the file.

Return value
Returns a string representing the absolute path.

Sample code

QDir dir("/home/user/documents");
qDebug() << "Absolute path:" << ();
qDebug() << "Absolute file path:" << ("");

Complete sample code

Here is a complete example showing how to use itQDirOperate files and directories:

#include &lt;QDir&gt;
#include &lt;QDebug&gt;
int main() {
    // Create QDir object    QDir dir("/home/user/documents");
    // Check whether the directory exists    if (!()) {
        qDebug() &lt;&lt; "Directory does not exist.";
        return -1;
    }
    // Create a subdirectory    if (("new_folder/sub_folder")) {
        qDebug() &lt;&lt; "Sub-directories created.";
    }
    // Get the list of files in the directory    QStringList filters;
    filters &lt;&lt; "*.txt";
    QStringList files = (filters, QDir::Files);
    qDebug() &lt;&lt; "Text files:" &lt;&lt; files;
    // Rename the file    if (("old_file.txt", "new_file.txt")) {
        qDebug() &lt;&lt; "File renamed.";
    }
    // Clear the directory    if (("new_folder")) {
        qDebug() &lt;&lt; "Directory removed.";
    }
    return 0;
}

Summarize

QDirIt is a comprehensive and flexible directory operation class, which allows developers to easily complete various tasks in the file system, such as creating, deleting, traversing directories and renaming files. By supporting filtering and sorting,QDirIt also provides fine-grained control capabilities. If your project needs to process files and directories,QDirIt is an indispensable tool.

This is all about this article about the Qt QDir path class. For more related Qt QDir path class content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!