Qt之QDesktopServices

来源:互联网 发布:手机cad制图软件 编辑:程序博客网 时间:2024/05/01 00:10

注:参考Qt大神一去二三里的博客

如果使用Qt开发界面,往往离不开QDesktopServices,QDesktopServices不仅可以打开本地浏览器,而且还可以打开本地文件(夹)等,可以获取桌面、我的文档、Home等目录。

使用前要加头文件

    #include  <QDesktopServices>

1、打开浏览器网页

QDesktopServices desktopServices;QUrl url(QString("www.baidu.com"));desktopServices.openUrl(url);

2、打开本地文件(夹)、可执行文件等

    QString local_path = QString("E:/新建文件夹"); //a.txt、a.exe、a.mp3、a.mp4、a.rmvb等    QString path = QString("file:///") + local_path;    bool is_open = QDesktopServices::openUrl(QUrl(path, QUrl::TolerantMode));  

注意:这里local_path可以是文件(夹)路径、可执行程序路径,当为文件时,会选择默认打开方式进行打开!

3、获取桌面、我的文档、Home等目录的路径

  QString desktop_path = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);  QString document_path = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);  QString home_path = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);  QString application_path = QDesktopServices::storageLocatio(QDesktopServices::ApplicationsLocation);  QString temp_path = QDesktopServices::storageLocation(QDesktopServices::TempLocation);

在这里再罗嗦一点,QProcess也可以打开文件(夹)、可执行程序等

  QString local_path = QString("E:\\新建文件夹");  bool is_start = QProcess::startDetached("explorer " + local_path);

本人项目中代码:Qt制作的PC软件中打开一个pdf或者word文档

    QDesktopServices desktopServices;    QString strUrl = QApplication::applicationDirPath () ;    strUrl = QString(QString::fromLocal8Bit("file:///%1/doc/readme.pdf")).arg (strUrl);    QUrl url(strUrl);    desktopServices.openUrl(url);
0 0