Linux 似乎很简单:xdg-open <file/directory/URL>
。
显然, Mac 类似:应使用open
代替xdg-open
。我无法访问Mac,因此无法对其进行测试。
对于 Windows ,我发现了4个不同的建议,而我尝试过的建议失败了。
How to give focus to default program of shell-opened file, from Java?建议
cmd /c start ...
How to open user system preferred editor for given file?
How to Find Out Default File Opener with Java?
建议
RUNDLL32.exe
What is the correct way to use ShellExecute() in C to open a .txt
Open file with Windows' native program within C++ code
How to use ShellExecute to open html files in Windows using C++?建议
ShellExecute
我已尝试使用system()
和QProcess::startDetached()
以及"http://www.stackoverflow.com"
作为参数的前3个,但它们都失败了; start
从命令行运行得很好。我还没有尝试ShellExecute
。
Windows等效于xdg-open
是什么?在我看来,它是start
,但为什么start
尝试失败?
ShellExecute
是我唯一的选择吗?
编辑我认为QDesktopServices::openUrl()
仅适用于网页,因为它不适用于文件或目录。
经过一些调试后,我发现如果我在Windows上的路径中用\\
替换/
,它适用于文件,但目录仍未打开。我有什么想法吗?
QDir dir("C:/Documents and Settings/ali");
qDebug() << "Exists? " << dir.exists();
qDebug() << dir.absolutePath();
QDesktopServices::openUrl(QUrl(dir.absolutePath()));
qDebug() << "External app called";
申请表输出:
Exists? true
"C:/Documents and Settings/ali"
External app called
但没有任何反应,目录未打开。在Linux上,按预期使用默认文件管理器打开目录。
解决方案:由于Qt错误和 Windows怪癖(格式错误的应用程序窗口),我最终使用了ShellExecute
。这给了我足够的灵活性,能够以某种代价实现我想要的......
答案 0 :(得分:17)
为什么不直接使用Qt的支持?例如:
QDesktopServices::openUrl(QUrl("/home/realnc/test.pdf"));
这将在Acrobat Reader中打开文档。通常,它遵循我的操作系统中针对具有一个或多个与之关联的应用程序的所有文件类型的首选应用程序设置。最重要的是,它与平台无关。
编辑: 它在Linux上打开目录而在Windows上打开目录的事实闻起来像一个bug。最好在Qt's bug tracker上报告此情况。与此同时,当文件是目录时,您可以使用Windows的解决方法:
#ifdef Q_WS_WIN
if (QFileInfo(path).isDir())
QProcess::startDetached("explorer", QStringList(path));
else
#endif
QDesktopServices::openUrl(QUrl(path));
您也可以使用cmd.exe的启动命令来执行此操作,但是您会在几分之一秒内弹出一个丑陋的终端:
QProcess::startDetached("cmd", QStringList() << "/C" << "start"
<< QDir::toNativeSeparators(path));