How to get Qt icon (QIcon) given file extension

I am developing an application that should display icons associated with different types of files .
For example, for .doc extensions, I need it to display the Microsoft Word icon.

Question:

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

Thanks.

+4
source share
3 answers
+8
source

Since Qt5, use QMimeDatabase for this:

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; } 
0
source

Unless you have a special requirement, QMimeDatabase is the best choice for your needs. I recommend you try @ nitro2005's answer. You can do this work manually using QFileIconProvider .

If you want to do this work with your own hand, but you cannot use QMimeDatabase for any reason, there is a solution for Linux / X11. You can use QFileInfo(const QString &file) to get the suffix / file extension (not necessarily about the QString you passed to the QFileInfo constructor is an existing path or not), and then get a MIME type that suffix finally you can get QIcon using QIcon::fromTheme and it is done.

For example, the following code will check whether the suffix of the ".bin" file, if any, give it an icon from the system theme with the MIME type "application-x-executable". In fact, it just maintains the MIME database itself.

 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 a link to a MIME string for your "MIME database", see the freedesktop badge naming specification .

0
source

Source: https://habr.com/ru/post/1334541/


All Articles