从Qt中的文件获取相对路径 [英] Get relative path from a file in Qt

查看:4276
本文介绍了从Qt中的文件获取相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我想写的文件中获取相对路径。这里的情况:

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

我在 D:\confs\conf.txt 中保存一个conf文件。我在我的程序有一些从 D:\images\image.bmp 读取的文件。在我的 conf.txt 我想有 ../ images / image.bmp

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.

我看到一些有用的类,如 QDir QFileInfo ,但我不知道它是最好的使用。我试过:

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

我读的文档,它说: filePath 只适用于dir集中的文件(这里 D:\confs ),但我不知道是否有一种方法来指示从不同的目录搜索并获得他的相对路径。

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.

推荐答案

您正在寻找以下方法:


QString QDir :: relativeFilePath(const QString& fileName)const

返回



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.

请注意缺失的引号。

这篇关于从Qt中的文件获取相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆