qt当前工程相对路径,从Qt中的文件获取相对路径

博客围绕在Qt中获取文件相对路径展开。作者尝试将D盘images文件夹下的文件路径以相对路径形式写入D盘confs文件夹下的配置文件,使用QDir和QFileInfo类遇到问题。文中给出解决方案,使用QDir的relativeFilePath方法,但也指出此做法可能使配置和图像路径耦合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am trying to get the relative path from files that I would like to write. Here a situation:

I save a conf file in D:\confs\conf.txt. I have in my programs some files read from D:\images\image.bmp. In my conf.txt I would like to have ../images/image.bmp.

I see some useful classes like QDir or QFileInfo but I don't know what it's the best to use. I tried:

QDir dir("D:/confs");

dir.filePath(D:/images/image.bmp) // Just return the absolute path of image.bmp

I read the doc and it says filePath only work with files in the dir set (here D:\confs) but I wonder if there is a way to indicate to search from a different dir and get his relative path.

解决方案

You are looking for the following method:

QDir dir("/home/bob");

QString s;

s = dir.relativeFilePath("images/file.jpg"); // s is "images/file.jpg"

s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt"

Adapting your code according to the examples above, it will look as follows:

QDir dir("D:/confs");

dir.relativeFilePath("D:/images/image.bmp") // Just return the absolute path of image.bmp

// ^ ^

Overall, what you do might be a bad idea since it will couple the config and image paths together. I.e. if you move either of them, the application stops working.

Please also notice the missing quotes.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值