首页 > 编程知识 正文

qt获取文件的绝对路径,qt记住上次打开文件路径

时间:2023-05-03 15:07:13 阅读:229252 作者:310

【转自:https://blog.csdn.net/andy_93/article/details/52831175】

 在项目中我们经常会遇到文件路径问题,如QFile file(“text.txt”)加载不成功、QPixmap("…/1.bmp") 加载图像不成功等问题。
 在能成功加载文件、图像之前,我们必须要弄清楚两个概念:绝对路径和相对路径
绝对路径:文件在硬盘上真正存在的路径。如QPixmap("…/1.bmp")这个图片是存放在系统的用户路径下,即:

这就是文件的绝对路径。
相对路径:由这个文件所在的路径引起的跟其它文件(或文件夹)的路径关系
 如当前file1的路径是/user/File/file1/file1.txt,
 File2的路径是/user/File/file2/file2.txt
 那么file2相对于file的路径就是“…/file2/file2.txt”。
 相对路径里常使用“…/”来表示上一级目录

弄清楚绝对路径和相对路径的概念后,再来弄清楚我们常用到的" ? “与” ./ "
./ : 表示当前路径, 如“./log/log1.txt” 表示当前路径下的log目录下 的log1.txt
? : 表示对资源的引用,引用资源文件路径,如“:/image/start.png”表示资源文件里面定义的文件start.png图像
明确以上概念之后,我们就可以明确文件路径怎样设置才能加载成功。

QT中常用的获取路径的函数
1 .获取应用程序可执行文件所在的目录: QCoreApplication::applicationDirPath();
QString applicationDirPath;
applicationDirPath = QCoreApplication::applicationDirPath();
qDebug()<<“applicationDirPath”<<applicationDirPath;

2.获取应用程序可执行文件的文件路径: QCoreApplication::applicationFilePath();
QString applicationFilePath;
applicationFilePath = QCoreApplication::applicationFilePath();
qDebug()<<“applicationFilePath”<<applicationFilePath;

3.获取应用程序当前工作目录的绝对路径:QString QDir::currentPath() /QDir::absolutePath() (这个类似于“./”操作)
QString currentPath;
QDir dir;
currentPath=dir.currentPath();
qDebug()<<“path”<<currentPath;

将相对路径转化为绝对路径:
QDir temDir("…/…/image.png");
QString filePath = temDir.absolutePath();
这样就获得了一个文件的绝对路径了。

QString applicationDirPath = QCoreApplication::applicationDirPath();qDebug() << "applicationDirPath = " << applicationDirPath;QString applicationFilePath = QCoreApplication::applicationFilePath();qDebug() << "applicationFilePath = " << applicationFilePath;QString currentPath;QDir dir;currentPath = dir.currentPath();qDebug() << "currentPath = " << currentPath;QString absolutePath = dir.absolutePath();qDebug() << "absolutePath = " << absolutePath;

结果:

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。