Christian
Christian

Reputation: 51

Recommended way of passing file paths in Qt application

in the codebase (C++ and Qt5) I am working on, filepaths are passed as QString parameters most of the time. In some cases it is also a combination of QDir and QString.

Examples:

void foo(const QString &filename);
void foo(const QDir pathToFile, const QString &filename);

In order to use stronger types for the interfaces, I was considering the following types:

QString This is the simplest, with the disadvantage that the type itself does not even tell that it is a path.

QDir Compared to QString we know that a path is passed. But still, it could be a path to a directory or a path to a file. Also the name QDir seems to be misleading for passing paths to files.

QFile For QFile it is clear that it is about a file, not about a directory. The thing I don't like about this is that it opens up other questions, such as "Should the passed file be opened before passing it? Does it need to exist?"

QFileInfo This seems to fit better than QFile, as it is a more lightweight class which is not used for modifying the file.

QUrl To me, this seems to be a too general-purpose class for passing file paths around.

std::filesystem::path This looks like it is a good equivalent to QDir. What I like, is that the name does not suggest that it is a directory. However I am not sure if mixing Qt and std:: classes here could cause other troubles i.e. native file paths.

Is there a recommended way for passing filepaths as parameters? Any thoughts are highly appreciated. My goal would be to have a guideline saying: When passing a path to a file, use class XYZ.

Upvotes: 3

Views: 1124

Answers (1)

László Papp
László Papp

Reputation: 53165

As someone, who has worked both on and with Qt, I should be biased, but I will not be. I will say that, in my opinion, always prefer to use the standard template library.

Even if you do not, always question yourself why not. And you need to have a good selling point. Qt has been trying too hard to get rid of obsolete Qt APIs that have been replaced by the recent std features.

So, unless you really have to, I would not go for the Qt equivalents, personally.

Now, of course, they are acceptable and OK if you have to confirm to an existing style. But there is little to no reason to hold unto Qt APIs when they are replaced by standard interfaces in C++.

We just need to move on and thank the corresponding Qt APIs that they have served us really well for so long and have probably been good inspiration for forming the next generation standards.

I would like to make it clear that this is not against Qt or any Qt API in particular. It is just life. APIs also age with us. And eventually, the ideal situation is when we can use the most from the standard.

Upvotes: 3

Related Questions