C++ 从 Qt 中的文件获取相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23998009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get relative path from a file in Qt
提问by user3627590
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
.
我在 .conf 文件中保存了一个 conf 文件D:\confs\conf.txt
。我的程序中有一些从D:\images\image.bmp
. 在我的conf.txt
我想拥有../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
orQFileInfo
但我不知道最好使用什么类。我试过:
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.
我阅读了文档,它说filePath
只适用于目录集中的文件(这里D:\confs
),但我想知道是否有一种方法可以指示从不同的目录搜索并获取他的相对路径。
采纳答案by lpapp
You are looking for the following method:
您正在寻找以下方法:
QString QDir::relativeFilePath(const QString & fileName) const
Returns the path to fileName relative to the directory.
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.
总的来说,你所做的可能是一个坏主意,因为它会将配置和图像路径耦合在一起。即,如果您移动其中任何一个,应用程序将停止工作。
Please also notice the missing quotes.
另请注意缺少的引号。
回答by ch0kee
QDir dir("D:/confs");
dir.relativeFilePath("D:/images/image.bmp");