How to get the icon for a file type on MacOS?

Viewed 57
1 Answers

Solution

To get the icon for a file use QFileIconProvider::icon with QFileInfo like that:

QIcon fileIcon = QFileIconProvider().icon(QFileInfo(fileName));

Example

Here is a simple example I wrote for you to demonstrate the proposed solution:

#include <QApplication>
#include <QFileIconProvider>
#include <QFileDialog>
#include <QFileInfo>
#include <QBoxLayout>
#include <QPushButton>

class Widget : public QWidget
{
public:
    Widget(QWidget *parent = nullptr) : QWidget(parent) {
        auto *l = new QVBoxLayout(this);
        auto *btnOpen = new QPushButton(tr("Open File"), this);

        btnOpen->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        l->addWidget(btnOpen);

        connect(btnOpen, &QPushButton::clicked, this, &Widget::onFileOpen);

        resize(300, 300);
    }

private slots:
    void onFileOpen() {
        const QString &fileName(QFileDialog::getOpenFileName(this, tr("Open File")));

        if (fileName.isEmpty())
            return;

        auto *btnOpen = static_cast<QPushButton *>(sender());

        btnOpen->setIcon(QFileIconProvider().icon(QFileInfo(fileName)));
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}
Related