QFileDialog :: getSaveFileName and default selectedFilter

I have getSaveFileName with some filters, and I want one of them to be selected when the user opens the Save dialog. The Qt documentation reads as follows:

You can select the default filter by setting the selectedFilter parameter to the desired value.

I try the following option:

QString selFilter="All files (*.*)"; QFileDialog::getSaveFileName(this,"Save file",QDir::currentPath(), "Text files (*.txt);;All files (*.*)",&selFilter); 

But when the dialog box appears, the Text Files filter is selected (in general, the first filter from the list). I also tried all of the following:

 selFilter="All files"; selFilter="All files (*.*)\n"; selFilter="All files (*.*);;"; selFilter="All files (*.*)\0"; 

and various mixtures of these options. The format of the filter list in my code is in accordance with the documentation (example line from Qt docs):

 "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)" 

Note that the output to the selFilter variable works correctly: after the user clicks OK, the selFilter variable contains a filter selected by the user.

Platform: Linux (OpenSUSE 12.1), Qt 4.7.4, gcc 4.6.2.

So how to set the default filter ?!

+6
source share
2 answers

The problem is partially resolved, it seems to be a bug in my version of Qt (4.7.4).

I wrote the following sample application:

 #include <QApplication> #include <QFileDialog> int main(int argc, char **argv) { QApplication app(argc,argv); QFileDialog::getSaveFileName(0,"Save file",QDir::currentPath(), "Music files (*.mp3);;Text files (*.txt);;All files (*.*)", new QString("Text files (*.txt)")); return 0; } 

and compiled it for three different platforms:

  • Linux (OpenSUSE 12.1), Qt 4.7.4, gcc 4.6.2
  • Linux (CentOS), Qt 4.7.3, gcc 4.1.2
  • MS Windows, Qt 4.8.1, gcc 4.4.0

On the first platform, the default dialog box was β€œMusic Files,” but on the second and third it was β€œText Files,” as it was.

0
source

You can try this app and check if it matters. When you use the direct construction of the dialog, as in this case you are more in control of the object.

 #include <QApplication> #include <QFileDialog> int main(int argc, char **argv) { QApplication app(argc,argv); QString filters("Music files (*.mp3);;Text files (*.txt);;All files (*.*)"); QString defaultFilter("Text files (*.txt)"); /* Static method approach */ QFileDialog::getSaveFileName(0, "Save file", QDir::currentPath(), filters, &defaultFilter); /* Direct object construction approach */ QFileDialog fileDialog(0, "Save file", QDir::currentPath(), filters); fileDialog.selectNameFilter(defaultFilter); fileDialog.exec(); return 0; } 

Typically, this behavior is a sign of memory corruption. However, I checked this with valgrind (I have Qt 4.8.1), and from FontConfig there are only some false positives.

+1
source

Source: https://habr.com/ru/post/926006/


All Articles