Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get relative path from a file in Qt

Tags:

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.

like image 539
user3627590 Avatar asked Jun 02 '14 15:06

user3627590


People also ask

How do you find relative path in Qt?

This is a relative path: QDir dir("../MyProjects/ProjectB"); If the current working directory is not a sub directory of "C:\MyDevelopment\", the path will be probably invalid (not existing). This will return the path to the passed name relative to the above directory.

How do I create a folder in Qt?

The only way I was able to create a folder was right-click on the 'MyApp' root folder in QtCreator, select 'Add New' and choose to add a new QML file. At that point, it brings up a file Browse dialog and you can navigate to the folder you created and drop the file in there.


2 Answers

You are looking for the following method:

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

Returns the path to fileName relative to the directory.

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.

like image 50
lpapp Avatar answered Sep 20 '22 14:09

lpapp


QDir dir("D:/confs"); dir.relativeFilePath("D:/images/image.bmp"); 
like image 31
ch0kee Avatar answered Sep 23 '22 14:09

ch0kee