How do I know which suffix user has selected when using QFileDialog?

Well, I use the following code to get the file name for the file to be saved.

QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),"/home/user/MyDocs/",tr("JPG files (*.jpg);;BMP files (*.bmp);;PNG files (*.png)")); 

I provide the user with a number of options regarding the file format in which the file should be saved. However, the returned QString gives me only the name of the prefix file that the user selected, not the suffix, and therefore I do not know which file format the user should choose. How to determine this file format?

+6
qt qfiledialog
source share
3 answers

Take a look at this discussion. It uses QFileInfo for the string entered in QFileDialog .

+2
source share

You need to use the 5th optional line
I usually do it like this:

 #define JPEG_FILES "JPG files (*.jpg)" #define BMP_FILES "BMP files (*.bmp)" #define PNG_FILES "PNG files (*.png)" QString selectedFilter; QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "/home/user/MyDocs/", JPEG_FILES ";;" BMP_FILES ";;" PNG_FILES, &selectedFilter); if (fileName.isNull()) return; if (selectedFilter == JPEG_FILES) { ... } else if (selectedFilter == BMP_FILES) { ... } else if (selectedFilter == PNG_FILES) { ... } else { // something strange happened } 

The compiler will take care of the concatenation of the literals in the argument.

I'm not sure how the returned string interacts with tr() . You will have to check and find out. probably need to translate it. It would be better if the function returned the index of the selected filter, but, alas, this is not so.

It would be best to put the filters in the list, create a string from it, and then compare those listed in the list with the returned selected filter string. This also solves the tr() problem.

+1
source share

The code in the question works on Windows (Qt 4.6.2 and Win XP). fileName contains the selected extension. But you obviously use something else Windows, so you can try this workaround:

 QFileDialog dialog(this, tr("Save as ..."), "/home/user/MyDocs/"); dialog.setAcceptMode(QFileDialog::AcceptSave); QStringList filters; filters << "JPG files (*.jpg)" << "BMP files (*.bmp)" << "PNG files (*.png)"; dialog.setNameFilters(filters); if (dialog.exec() == QDialog::Accepted) { QString selectedFilter = dialog.selectedNameFilter(); QString fileName = dialog.selectedFiles()[0]; } 

This is a slightly modified code from here .

+1
source share

All Articles