QFileDialog setNameFilter can be fooled

  • Let's say I want a QFileDialog that can open only specific extensions. I do this:

    m_dialog.setOption(QFileDialog::ReadOnly, true);
    m_dialog.setNameFilter(tr("Models (*.jpg)"));
    m_dialog.setOption(QFileDialog::ReadOnly, true);

    Unfortunately, I still can write a filename by hand in the textbox and it will be opened even if its extension is not listed in the setNameFilter arguments.

    I thought that maybe that's the 'feature' of the windows native window, so I set

    m_dialog.setOption( QFileDialog::DontUseNativeDialog);

    and 'Open' button in the dialog became disabled. Unfortunately, writing filename by hand and pressing 'Enter' still opens incorrect file.

    So I have to filter by extension twice.

    I just want to know, if that behaviour is normal or if it's a bug in Qt.

  • Lifetime Qt Champion


    What version of Qt are you using on which platform ?

  • @SGaist I'm using QT 5.7.1 on Windows.

  • Lifetime Qt Champion

    Can you validate that with a more recent version of Qt ?

    Note that I suspect that it's a Windows specific behaviour. By default Qt uses the native file dialog which may have some quirks.

  • @Amomum
    You want the filter to actually prevent a user from being able to specify a filename with a certain extension. But I don't think "filters" have ever claimed to do that. From the docs:

    In the above example, the filter is set to "Images (*.png *.xpm *.jpg)", this means that only files with the extension png, xpm, or jpg will be shown in the QFileDialog.

    I think they only determine what filenames are shown for selection. If the user types something, I don't they have anything to do with validating the response.

    So, yes, for safety you have to validate the final result yourself if it matters.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.