qtfile-extensionqlistqfileinfo

check if a file extension is part of a given list


I am trying to make a simple widget which contains a lineedit which shows the file name and a button to open a filedialog. and now I want to check if the file-extension is valid, in this case, a image file ending with jpg, png or bmp. I solved this with QFileInfo and QList, this code is in my btn_clicked slot:

QString filename = QFileDialog::getOpenFileName(this, tr("Select an image File", "", tr("Image Files (*.bmp *.jpg *.png);; All Files(*)"));
QList<QString> ext_list;
ext_list<<"bmp"<<"jpg"<<"png";
QFileInfo fi(filename);
QString ext = fi.suffix();
if (ext_list.contains(ext)){
   // lineedit->setText(filename);
}
else {
QMessageBox msgBox;
msgBox.critical(0, "Error", "You must select a valid image file");

it works, but is there a more simple/elegant way to achieve the goal? Thx for your help.


Solution

  • You might be interested by the setNameFilters function : http://doc.qt.io/qt-5/qfiledialog.html#setNameFilters

    Update

    If you want to filter images without naming each extensions, you should use QMimeDatabase. This will allow you to define your filter for the QFileDialog and then get a list of extensions to check.

    For example with jpeg and png:

    QStringList mimeTypeFilters;
    mimeTypeFilters << "image/jpeg" << "image/png";
    
    QFileDialog fd;
    fd.setFileMode(QFileDialog::ExistingFile);
    fd.setMimeTypeFilters(mimeTypeFilters);
    fd.exec();
    
    QString filename = fd.selectedFiles().count() == 1 ? fd.selectedFiles().at(0) : "";
    
    QMimeDatabase mimedb;
    if(!mimeTypeFilters.contains(mimedb.mimeTypeForFile(filename).name()))
    {
        // something is wrong here !
    }