检查文件扩展名是否是给定列表的一部分

时间:2020-12-06 20:07:01

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:

我正在尝试制作一个简单的小部件,其中包含一个显示文件名的lineedit和一个用于打开filedialog的按钮。现在我想检查文件扩展名是否有效,在这种情况下,是一个以jpg,png或bmp结尾的图像文件。我用QFileInfo和QList解决了这个问题,这个代码在我的btn_clicked插槽中:

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.

它有效,但有没有更简单/优雅的方式来实现目标?谢谢你的帮助。

1 个解决方案

#1


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

您可能对setNameFilters函数感兴趣: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.

如果要在不指定每个扩展名的情况下过滤图像,则应使用QMimeDatabase。这将允许您为QFileDialog定义过滤器,然后获取要检查的扩展列表。

For example with jpeg and png:

例如,使用jpeg和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 !
}

#1


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

您可能对setNameFilters函数感兴趣: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.

如果要在不指定每个扩展名的情况下过滤图像,则应使用QMimeDatabase。这将允许您为QFileDialog定义过滤器,然后获取要检查的扩展列表。

For example with jpeg and png:

例如,使用jpeg和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 !
}