Qt之根据扩展名获取文件图标、类型

简述

C++根据扩展名获取文件图标、类型一节中我们分享了如何根据扩展名来获取对应的文件图标、类型,下面。我们在Qt中使用它。

示例

如下,我们根据扩展名来获取对应的文件图标、类型。

效果

这里写图片描述

源码

首先在pro中添加winextras模块:

QT += winextras

然后,在源码中包含:#include <QtWin>,之后,方可使用。

std::string strArray[13] = {"folder", ".exe", ".zip", ".har", ".hwl", ".accdb",
                                ".xlsx", ".pptx", ".docx", ".txt", ".h", ".cpp", ".pro"};
int nCount = sizeof(strArray) / sizeof(std::string);
for (int i = 0; i < nCount ; ++i)
{
    // 获取图标、类型
    QPixmap pixmap;
    std::string type;
    int nPos = -1;
    nPos = strArray[i].find(".");
    if (nPos >= 0)
    {
        // Qt4:QPixmap::fromWinHICON(icon)
        pixmap = QtWin::fromHICON(fileIcon(strArray[i]));
        type = fileType(strArray[i]);
    }
    else
    {
        pixmap = QtWin::fromHICON(folderIcon());
        type = folderType();
    }

    QIcon icon;
    icon.addPixmap(pixmap);
    QString strType = QString::fromLocal8Bit(type.c_str());

    // 添加单元项
    QListWidgetItem *pItem = new QListWidgetItem(pListWidget);
    pItem->setIcon(icon);
    pItem->setText(strType);
    pListWidget->addItem(pItem);
}

在Qt4中,可以通过QPixmap::fromWinHICON(HICON)来转换,但是,到了Qt5以后此接口已经被遗弃了,所以这里使用QtWin::fromHICON(HICON)。

更多参考

posted @ 2016-07-04 17:46  挨踢人啊  阅读(832)  评论(0编辑  收藏  举报