您的位置:首页 > 编程语言 > Qt开发

Qt获取程序路径 之 QDir::currentPath与qApp->applicationDirPath

2018-01-11 09:50 2026 查看
Qt获取程序路径 之 QDircurrentPath与qApp-applicationDirPath
前言

解决办法
qApp-applicationDirPath

QDirCurrentDir

官方定义

Qt获取程序路径 之 QDir::currentPath()与qApp->applicationDirPath()

前言

一直使用QDir::currentPath()来获取程序所在绝对路径,根据路径在指定目录创建合适的文件夹。但是最近程序在开发板运行时文件夹创建的路径突然不对了。打印出来发现程序获取路径出错。

该现象与程序的启动方式有关。使用绝对路径,相对路径和开机自启时获取的路径不一样。

解决办法

使用qApp->applicationDirPath() 替换 QDir::currentPath()


qApp->applicationDirPath()

无论你通过何种途径去运行文件,QAppllication::appllicationDirPath()的路径始终都是可执行文件所在的绝对路径。

QDir::CurrentDir()

(1)在vs2010中,之间按F5调试,QDir::currentPath()为“盘符:\工程名\工程名”(也就是从cpp和.h文件所在的路径,如:E:\vs2010\qt\QtProjects\tenNumAdd\tenNumAdd).

(2)直接到vs2010工程相应的目录下(Debug或Release)去双击exe文件,QDir::currentPath()为“盘符:\工程名\工程名\Debug”,如:E:\vs2010\qt\QtProjects\tenNumAdd\tenNumAdd\Debug.

(3)通过cmd的命令启动相应的exe文件(如:start

E:\vs2010\qt\QtProjects\tenNumAdd\tenNumAdd\Debug***.exe),QDir::currentPath()为:C:\用户名。如果此时我所在的用户名为administrator,则QDir::currentPath()为C:\administrator。

由此可见,QDir::currentPath()在第三种情况下就不是我们想要的了。

( 参考:http://blog.csdn.net/bzhxuexi/article/details/38087119

官方定义

QString QDir::currentPath() [static]

Returns the absolute path of the application’s current directory. The current directory is the last directory set with QDir::setCurrent() or, if that was never called, the directory at which this application was started at by the parent process.

这是一个静态方法,返回应用程序的当前路径(以绝对路径表示).当前目录是最近一次调用QDir::setCurrent()设置的值,如果彼函数未被调用过,当前目录即是被父进程开启时的目录

QString QCoreApplication::applicationDirPath() [static]

Returns the directory that contains the application executable.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐