[Qt-interest] QFileDialog::getOpenFileName Directory name

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Wed Jun 9 13:21:54 CEST 2010


K. Frank wrote on Wednesday, June 09, 2010 3:58 AM:

> ...
> But note in my test (done with windows-style "\" rather than
> unix-style "/")

First off, the entire Qt API (QFile, QFileInfo, ...) which deals with file paths accepts "Unix-style" delimiters ('/') - on ALL platforms. So when hardcoding paths it is best to always use the '/' delimiter instead of the platform-specific one. Works on all platforms ;)

(Off course on Windows also the platform-specific path delimiter is accepted, but remember to escape it properly when hardcoding paths!)

Then the proper path to a directory is terminated with a '/' - otherwise you would specify a file! Unfortunatelly AFAICR Qt is not entirely consistent with this either, some methods return a directory without delimiting '/' in the end, e.g. http://doc.trolltech.com/4.6/qfileinfo.html#absolutePath. But this might have changed, did not check recently.

So: 

/foo/bar/baz/ - is a directory
/foo/bar/baz - is a file 'baz' with absolute path /foo/bar/  (1)

That said, it should be aboslutely clear that

QString filePath = QFileDialog::getOpenFileName(this, "Caption", "/foo/bar/baz/");

and

QString initialDir = "/foo/bar/baz/";
QString filePath = QFileDialog::getOpenFileName(this, "Caption", initialDir);

is semantically absolutely the same - if that doesn't work, then your compiler is broken (or more likely, you did another mistake which you removed when posting your example).

Note that in both examples, the "C-style" string "/foo/bar/baz/" is "auto-boxed" into a QString, by implicitly calling the "conversion c'tor"

  QString(const char *str);
  http://doc.trolltech.com/4.6/qstring.html#QString-7

(See also http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr384.htm - but again, this is basic C++ knowledge).

Qt offers a QT_NO_CAST_FROM_ASCII define which prevents this implicit "c-style string" to QString conversion when defined (because it can be costly and dangerous). But as long as you did not play around with this DEFINE (and you would get a compiler error anyway if you did with above examples) the code above behaves the same.

Cheers, Oliver

(1) The reason why URLs like http://www.foocompany.com/directory work in browsers (instead of correctly http://www.foocompany/directory/) is because the browser is so clever upon the first 404 Not Found to say "Hmm, the user probably meant a DIRECTORY instead of a file 'directory') and appends a '/' and does a SECOND request in the background! Only then does the server reply with the default index.html (or whatever default file) in that directory.
-- 
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22



More information about the Qt-interest-old mailing list