use*_*590 19 c++ qt qdir qtcore qfileinfo
我试图从我想写的文件中获取相对路径.这里有一个情况:
我保存了一个conf文件D:\confs\conf.txt.我在我的程序中有一些文件从中读取D:\images\image.bmp.在我conf.txt想要的../images/image.bmp.
我看到一些有用的课程QDir,QFileInfo但我不知道它最好用什么.我试过了:
QDir dir("D:/confs");
dir.filePath(D:/images/image.bmp) // Just return the absolute path of image.bmp
Run Code Online (Sandbox Code Playgroud)
我阅读了文档,它说filePath只能处理目录集中的文件(这里D:\confs),但我想知道是否有办法指示从不同的目录搜索并获得他的相对路径.
lpa*_*app 17
您正在寻找以下方法:
QString QDir :: relativeFilePath(const QString&fileName)const
返回相对于目录的fileName的路径.
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"
Run Code Online (Sandbox Code Playgroud)
根据上面的示例调整您的代码,它将如下所示:
QDir dir("D:/confs");
dir.relativeFilePath("D:/images/image.bmp") // Just return the absolute path of image.bmp
// ^ ^
Run Code Online (Sandbox Code Playgroud)
总的来说,你所做的可能是个坏主意,因为它会将配置和图像路径耦合在一起.即如果你移动它们中的任何一个,应用程序就会停止工作.
还请注意缺少的引号.