How to create a new QDir from an existing QDir + a subfolder?
-
I have an existing QDir. I want a QDir for a folder inside. E.g.
void someMethod(QDir input) { QDir folderInInput = input.path() + "/SubfolderName"; doStuff(folderInInput); ... }
Normally, scripting languages will you allow to do something like
QDir folderInput = input / "SubfolderName"
, but Qt doesn't. I could just use what I have above, but I'm not a fan of it because it hardcodes the slash. I could doinput.path() + QDir::separator() + "SubfolderName"
, but that's too verbose. Does Qt have a more desirable way to index a subfolder of an existing QDir? -
Hi @EchoReaper and welcome
I'm not entirely sure what you try to do here, as doStuff seems to be a local function, but QDir offers a change directory function
cdUp to go one directory up and
cd(folderName) to change to a sub directoryIf that is what you're looking for?
-
cd kind of does what I want, but I want to create a new QDir rather than modifying an existing one. cd doesn't really make sense because of the variable names e.g.
QDir getDownloads(QDir userProfile) { userProfile.cd("Downloads"); return userProfile; }
We say we're returning
userProfile
, but we're not actually. We've changed the QDir to something else. I could clone the QDir and then change that, but that wouldn't be so elegant either. Preferred:QDir getDownloads(QDir userProfile) { QDir downloads = userProfile.subfolder("Downloads"); maybeDoStuffWithQDirIfThisIsNotSuchASimpleMethod(downloads); return downloads; }
-
@EchoReaper
Well no, there is no function in the QDir class that returns a new dir, at least not in the way you want it.You could use the copy constructor?
Dir newDir(oldDir).cd("Downloads");
-
I guess that will do. Thanks!
-
@EchoReaper said in How to create a new QDir from an existing QDir + a subfolder?:
Normally, scripting languages will you allow to do something like QDir folderInput = input / "SubfolderName", but Qt doesn't. I could just use what I have above, but I'm not a fan of it because it hardcodes the slash. I could do input.path() + QDir::separator() + "SubfolderName", but that's too verbose. Does Qt have a more desirable way to index a subfolder of an existing QDir?
I would say the "correct" Qt way of producing the path to a sub-folder, without using
/
orQDir::separator()
the way you have (which isn't great if your starting directory ends with a/
, like/
orC:/
, e.g. whenQDir::isRoot() == true
), is to use https://doc.qt.io/qt-5/qfileinfo.html#setFile-2,void QFileInfo::setFile(const QDir &dir, const QString &file)
.You/Qt don't know whether the sub-item is a file or directory, that's why it's a
QFileInfo
method rather than aQDir
one. You can then, say, feedQFileInfo::absoluteFilePath()
to a newQDir()
if you want to access it as a directory.If you actually wish to create the sub-directory you could use https://doc.qt.io/qt-5/qdir.html#mkdir or https://doc.qt.io/qt-5/qdir.html#mkpath.