python - 从外部应用程序获取图标
问题描述
我正在尝试准备一个类似于“Windows 开始菜单搜索”的应用程序。
这就是为什么我需要每个应用程序都有自己的图标。
从C:\ProgramData\Start Menu\Programs\
文件路径中,我将现有应用程序(QListWidget)
及其名称和路径添加到列表中。
我得到这样的图标: https ://forum.qt.io/topic/62866/getting-icon-from-external-applications
provider = QFileIconProvider()
info = QFileInfo("program_path")
icon = QIcon(provider.icon(info))
但我不希望出现这个“快捷方式图标”。
然后,我在想,我得出了这个结论:
shell = win32com.client.Dispatch("WScript.Shell")
provider = QFileIconProvider()
shortcut = shell.CreateShortCut(programPath)
info = QFileInfo(shortcut.targetPath)
icon = QIcon(provider.icon(info))
这个解决方案奏效了。但是,它为某些应用程序带来了问题。所以我正在寻找替代解决方案。
解决方案
你快到了。
浏览菜单目录树实际上是正确的路径,但您还必须确保链接的图标实际上与目标相同,因为它可能不一样。
这shortcut.iconlocation
是一个字符串,表示“元组”(某种),包括图标路径和索引(因为图标资源可能包含多个图标)。
>>> shortcut = shell.createShortCut(linkPath)
>>> print(shortcut.iconlocation)
# most links will return this:
> ",0"
# some might return this:
> ",4"
# or this:
> "C:\SomePath\SomeProgram\SomeExe.exe,5"
只要图标索引为 0,您就可以使用带有targetPath
或的 QFileIconProvider 获取图标iconLocation
(如果逗号前有东西)。
当图标索引的值不同于 0 时,问题就出现了,因为 Qt 没有处理这个问题。
我整理了一个简单的函数(基于 StackOverflow 上的一些研究) 。
def getIcon(self, shortcut):
iconPath, iconId = shortcut.iconLocation.split(',')
iconId = int(iconId)
if not iconPath:
iconPath = shortcut.targetPath
iconPath = os.path.expandvars(iconPath)
if not iconId:
return QICon(self.iconProvider.icon(QFileInfo(iconPath)))
iconRes = win32gui.ExtractIconEx(iconPath, iconId)
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
# I think there's a way to find available icon sizes, I'll leave it up to you
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), iconRes[0][0])
hdc.DeleteDC()
# the original QtGui.QPixmap.fromWinHBITMAP is now part of the
# QtWin sub-module
return QtGui.QIcon(QtWin.fromWinHBITMAP(hbmp.GetHandle(), 2))
推荐阅读
- .net - 从 Sap.Data.Hana.HanaDataRader 获取字段名称
- javascript - 如何通过 Axios.get() 中的 URL 渲染图像
- javascript - React 中处理竞争的 Ajax 请求的方式是什么,所以只有最后一个通过?
- javascript - 跨用户的外语语音识别结果差异很大
- c - 如何扫描从另一个 c 程序运行的输出字符串值?
- python - 仅当列数超过 1 时才解析 CSV 文件的条件
- c# - 使用 utf 字符命名变量
- excel - 如何在 Excel 中将信息从一张表复制到另一张表
- angular - Karma 和 Jasmine 使用 Angular 7 注入服务测试 - StaticInjectorError(DynamicTestModule)[I18n -> InjectionToken TranslationsFormat]
- php - 多对多(多态)使用具有不同类型的相同模型