我正在使用PySide(包装Qt 4.8框架)开发一个应用程序。我需要显示与某些文件扩展名相关联的应用程序图标,我正在使用QFileIconProvider
。在Windows上,我的代码完美运行 - 每个文件扩展名都与相应应用程序的图标一起显示。但是,在Linux Ubuntu(14.04.1)上,相同的代码显示了我尝试的所有文件扩展名的未知文件扩展名的图标。
任何人都知道为什么会这样吗?这是代码:
from PySide import QtCore, QtGui
# Use the appropriate path module when running on Windows.
path = None
import os
if os.name == "nt":
path = __import__("ntpath")
else:
path = os.path
class MyWidget(QtGui.QWidget):
def __init__(self, *args, **kwargs):
# ...
# ...
self.file_ext_to_icon = {}
def get_icon(self, fpath):
_, file_ext = path.splitext(fpath)
file_ext = file_ext.replace(".", "")
if file_ext in self.file_ext_to_icon:
return self.file_ext_to_icon[file_ext]
if path.exists(fpath):
icon = QtGui.QFileIconProvider().icon(QtCore.QFileInfo(fpath))
else:
temp_fpath = path.join(os.getcwd(), "myappname_temp.%s" % file_ext)
if not path.exists(temp_fpath):
with open(temp_fpath, "wb") as _:
pass
icon = QtGui.QFileIconProvider().icon(QtCore.QFileInfo(temp_fpath))
os.remove(temp_fpath)
if icon.isNull():
# Use a custom default file icon from the resources file. Note that
# this is different from the default file icon given by the OS.
icon = QtGui.QIcon(":images/default_file_icon.png")
self.file_ext_to_icon[file_ext] = icon
return icon
答案 0 :(得分:0)
我遇到了同样的问题,经过多次挖掘后我才最终做到了......
class IconProvider(QtWidgets.QFileIconProvider):
def __init__(self):
super().__init__()
self.mimeDatabase = QtCore.QMimeDatabase()
def icon(self, info: QtCore.QFileInfo):
mimeType = self.mimeDatabase.mimeTypeForFile(info)
return QtGui.QIcon.fromTheme(mimeType.iconName())
...used in my class
self.filesModel = QtWidgets.QFileSystemModel(self.filesView)
self.filesModel.setIconProvider(IconProvider())
...or in your case
icon = IconProvider().icon(QtCore.QFileInfo(fpath))