Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat a QString as a file location and get its directory

Tags:

c++

qt

I gather a list of files into a QStringList from a Qt GUI. Each of these files is a .txt file, with a corresponding video file in same_folder_as_txt/videos/.

Is there an easy way to manipulate QString objects as file paths? For example, given C:/some/path/foo.txt , I want to retrieve C:/some/path/videos/foo.avi

like image 337
Jim Avatar asked Sep 06 '12 13:09

Jim


People also ask

How do I open a QT file in C++?

Try to put it in the same directory as the executable or just put the complete path into the QFile constructor. Print out the string returned by QDir::currentPath(); I bet it's different from the path where the trace. txt file is located at.

How do you convert QString to string?

You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.

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.

How do I write a QT file?

To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right: QFile file("out. txt"); if (! file.


2 Answers

Given your path as a QString s

info = QFileInfo(s)
// Get the name of the file without the extension
base_name = info.baseName()
// Add a ".avi" extension
video_file = QStringList((base_name, "avi")).join(".")
// Get the directory
dir_name = info.path()
// Construct the path to the video file
video_path = QStringList((dir_name, QString("videos"), video_file).join("/")
like image 198
Pierre GM Avatar answered Nov 15 '22 05:11

Pierre GM


You can convert them each to QDir, perform your modifications as a path, and then use absolutePath() to get the QString back.

like image 27
cmannett85 Avatar answered Nov 15 '22 05:11

cmannett85