How to launch the associated application for a file / directory / URL?

Ali picture Ali · Dec 7, 2012 · Viewed 7.7k times · Source

Linux seems to be easy: xdg-open <file/directory/URL>.

Apparently, Mac is similar: open should be used instead of xdg-open. I don't have access to a Mac so I couldn't test it.

For Windows, I found 4 different suggestions and those that I have tried failed.

I have tried the first 3 with system() and QProcess::startDetached() and "http://www.stackoverflow.com" as argument but they all failed; start works just fine from the command line though. I haven't tried ShellExecute yet.

What is the Windows equivalent of xdg-open? It seem to me, it is start but why did my attempts with start fail?

Is ShellExecute my only option?


EDIT I thought QDesktopServices::openUrl() was for web pages only because it did not work for files or directories.

After some debugging I figured out that if I replace \\ with / in the path on Windows, it works for files but the directories are still not opened. Any ideas what I am doing wrong?

QDir dir("C:/Documents and Settings/ali");

qDebug() << "Exists? " << dir.exists();

qDebug() << dir.absolutePath();

QDesktopServices::openUrl(QUrl(dir.absolutePath()));

qDebug() << "External app called";

Application Output:

Exists?  true 
"C:/Documents and Settings/ali" 
External app called 

But nothing happens, the directory is not opened. On Linux, directories are opened with the default file manager as expected.


SOLUTION: Due to the Qt bug and Windows quirks (malformed application window), I ended up using ShellExecute. That gives me enough flexibility to achieve exactly what I want at some expense...

Answer

Nikos C. picture Nikos C. · Dec 7, 2012

Why don't you just use Qt's support for this? For example:

QDesktopServices::openUrl(QUrl("/home/realnc/test.pdf"));

This opens the document in Acrobat Reader. In general, it obeys the preferred application settings in my OS for all file types that have one or more applications associated with them. Best of all, it's platform-independent.

Edit: The fact that it opens directories on Linux but not on Windows smells like a bug. It might be best to report this on Qt's bug tracker. In the meantime, you could have a workaround for Windows for when the file is a directory:

#ifdef Q_WS_WIN
    if (QFileInfo(path).isDir())
        QProcess::startDetached("explorer", QStringList(path));
    else
#endif
        QDesktopServices::openUrl(QUrl(path));

You can also do it with cmd.exe's start command, but you'll get an ugly terminal pop up for a few fractions of a second:

QProcess::startDetached("cmd", QStringList() << "/C" << "start"
                               << QDir::toNativeSeparators(path));