36

I have a open file dialog with three filters:

QString fileName = QFileDialog::getOpenFileName(
        this,
        title,
        directory,
        tr("JPEG (*.jpg *.jpeg);; TIFF (*.tif);; All files (*.*)")
);

This displays a dialog with "JPEG" selected as the default filter. I wanted to put the filter list in alphabetical order so "All files" was first in the list. If I do this however, "All files" is the default selected filter - which I don't want.

Can I set the default selected filter for this dialog or do I have to go with the first specified filter?

I tried specifying a 5th argument (QString) to set the default selected filter but this didn't work. I think this might only be used to retrieve the filter that was set by the user.

Nejat
  • 31,784
  • 12
  • 106
  • 138
Greg K
  • 10,770
  • 10
  • 45
  • 62

2 Answers2

56

Like this:

QString selfilter = tr("JPEG (*.jpg *.jpeg)");
QString fileName = QFileDialog::getOpenFileName(
        this,
        title,
        directory,
        tr("All files (*.*);;JPEG (*.jpg *.jpeg);;TIFF (*.tif)" ),
        &selfilter 
);

The docs are a bit vague about this, so I found this out via guessing.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
shoosh
  • 76,898
  • 55
  • 205
  • 325
  • That's the solution I came up with too, but I actually think it is a bad API here. What if you want to keep the last filter used by the user ? The 5th parameter is a non const pointer, but little will it update itself to the last used filter string. You'd have to manually extract the loaded file extension and construct the right string for it. It makes no sense it being non const, or there is something I didn't get. One solution is to instantiate a QFileDialog manually, but it kinda feels too bad. – foxesque Jul 27 '20 at 04:40
  • As of Qt 6.5 that 5th parameter will indeed update itself to the filter selected by the user upon closing of the dialog, so you can reuse that selection next time the dialog is shown – ray_ray_ray Jun 11 '23 at 13:57
2

Here is a string for all of the QT supported image formats.

"All files (*.*);;BMP (*.bmp);;CUR (*.cur);;GIF (*.gif);;ICNS (*.icns);;ICO (*.ico);;JPEG (*.jpeg);;JPG (*.jpg);;PBM (*.pbm);;PGM (*.pgm);;PNG (*.png);;PPM (*.ppm);;SVG (*.svg);;SVGZ (*.svgz);;TGA (*.tga);;TIF (*.tif);;TIFF (*.tiff);;WBMP (*.wbmp);;WEBP (*.webp);;XBM (*.xbm);;XPM (*.xpm)"
kblst
  • 493
  • 8
  • 12