Jim
Jim

Reputation: 4669

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

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

Upvotes: 5

Views: 7885

Answers (2)

Pierre GM
Pierre GM

Reputation: 20339

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("/")

Upvotes: 11

cmannett85
cmannett85

Reputation: 22346

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

Upvotes: 7

Related Questions