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

橙三吉。 提交于 2019-12-10 15:29:37

问题


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.



来源:https://stackoverflow.com/questions/4617981/how-to-get-qt-icon-qicon-given-a-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!