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

前端 未结 1 688
死守一世寂寞
死守一世寂寞 2021-02-14 06:29

Linux seems to be easy: xdg-open .

Apparently, Mac is similar: open should be used

相关标签:
1条回答
  • 2021-02-14 06:49

    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));
    
    0 讨论(0)
提交回复
热议问题