Important: Please read the Qt Code of Conduct -

Copy folder qt c ++

  • How can i copy a folder to another directory?

  • Lifetime Qt Champion

    You can use QFile::copy to copy all files to new folder.
    If you need to do it recursively, Qt has functions for that too that you can combine to a working function.

  • @mrjj tnks

  • Moderators

    @Nathan-Miguel Keep in mind that those stackoverflow solutions use recursion, which may result in (ironically) stack overflow with deeply nested directories. Also, if there's a lot of files QDir::entryList will return a large list, which might require large amount of memory.
    A better solution might be using QDirIterator with QDirIterator::Subdirectories which uses resources only for one entry at a time.

  • Moderators

    Since QDir & QDir::EntryList has some serious trouble with (MacOS) app-bundles, I ended up implementing the QDirIterator solution @Chris-Kawa suggested:

    void copyAndReplaceFolderContents(const QString &fromDir, const QString &toDir, bool copyAndRemove = false) {
        QDirIterator it(fromDir, QDirIterator::Subdirectories);
        QDir dir(fromDir);
        const int absSourcePathLength = dir.absoluteFilePath(fromDir).length();
        while (it.hasNext()){
            const auto fileInfo = it.fileInfo();
            if(!fileInfo.isHidden()) { //filters dot and dotdot
                const QString subPathStructure = fileInfo.absoluteFilePath().mid(absSourcePathLength);
                const QString constructedAbsolutePath = toDir + subPathStructure;
                    //Create directory in target folder
                } else if(fileInfo.isFile()) {
                    //Copy File to target directory
                    //Remove file at target location, if it exists, or QFile::copy will fail
                    QFile::copy(fileInfo.absoluteFilePath(), constructedAbsolutePath);

Log in to reply