How to get Qt icon (QIcon) given a file extension

2019-06-22 16:14发布

问题:

I am developing an application that needs to display icons associated with different file types.
Eg for .doc extensions, i need it to be able to display the Microsoft Word icon.

QUESTION:

How can I somehow get a QIcon from the system using QT sdk

Thanks.

回答1:

Use the QtGui.QFileIconProvider class.



回答2:

Since Qt5, use QMimeDatabase for that:

QMimeDatabase mime_database;

QIcon icon_for_filename(const QString &filename)
{
  QIcon icon;
  QList<QMimeType> mime_types = mime_database.mimeTypesForFileName(filename);
  for (int i=0; i < mime_types.count() && icon.isNull(); i++)
    icon = QIcon::fromTheme(mime_types[i].iconName());

  if (icon.isNull())
    return QApplication::style()->standardIcon(QStyle::SP_FileIcon);
  else
    return icon;
}


回答3:

If you don't have special requirement, QMimeDatabase is a better choice for your need. I recommend you try @nitro2005's answer. You can still do this work by your hand by using QFileIconProvider.

If you want to do this work by your hand but you can't use QMimeDatabase for some reason, there is a solution works for Linux/X11. You can use QFileInfo(const QString &file) to get the file's suffix / extension (It's not necessary about the QString you passed to the QFileInfo constructor is a exist path or not), and then get the MIME type form that suffix, at last you can get the QIcon by using QIcon::fromTheme and it's done.

For example, the following code will check if file's suffix is ".bin", if is, the give it a icon from the system theme with "application-x-executable" MIME type. In fact it's just maintaining a MIME database by your self.

QString fileName("example.bin");
QFileInfo fi(fileName);
if (fi.suffix().compare(QString("bin")) == 0) {
    item->setIcon(QIcon::fromTheme("application-x-executable",
                                    provider.icon(QFileIconProvider::File)));
}

To get the MIME type string reference for your "MIME database", please checkout the freedesktop icon naming spec.