Search code examples
python-3.xwindowsqtpyqt5system

How to use system default icons for a file type in a QTreeView


for reference this is all using Pyqt5 and Python 3.6:

I've got a QStandardItemModel that is built from QStandardItems that are strings of the items in a zip (the model displays all the contents of a zipfile). I went with this choice as I can not cache the files locally, and my research shows that QFileSystemModel can not work on archives unless I unpack at least temporarily.

All items in the QStandardItemModel end in the correct extension for the file (.csv,.txt,ect), and I need to display the icon a user would see if they were looking at the file in windows explorer, however show it in the qtreeview (a user seeing content.csv should also see the icon for excel). On that note, this application is only running on windows.

How can I pull the extensions default system file icon, and set it during my setting of these items? Would I have to manually download the icons for my known file types and do this, or does the system store it somewhere I can access?

Here's some basic code of how I build and display the model and treeview:

        self.zip_model = QtGui.QStandardItemModel()

        # My Computer directory explorer
        self.tree_zip = QTreeView()
        self.tree_zip.setModel(self.zip_model)

    def build_zip_model(self,current_directory):
        self.zip_model.clear()
        with zipfile.ZipFile(current_directory) as zip_file:
            for item in zip_file.namelist():
                model_item = QtGui.QStandardItem(item)
                self.zip_model.appendRow(model_item)

Solution

  • You can use QFileIconProvider:

    def build_zip_model(self, current_directory):
        iconProvider = QtWidgets.QFileIconProvider()
        self.zip_model.clear()
        with zipfile.ZipFile(current_directory) as zip_file:
            for item in zip_file.namelist():
                icon = iconProvider.icon(QtCore.QFileInfo(item))
                model_item = QtGui.QStandardItem(icon, item)
                self.zip_model.appendRow(model_item)