本来是可以加载PyQt5插件的,但在conda中安装多个包含PyQt5的虚拟环境后,导致其在运行时无法正确识别到插件路径。

在windows中的conda虚拟环境运行一个PyQt5程序,出现如下错误:

This application failed to start because it could not find or load the Qt platform plugin "windows"
in "".

原因:Qt platform plugin "windows" 未正确加载。

运行以下测试脚本确认是否可以加载插件:

>>> from PyQt5.QtCore import QLibraryInfo
>>> print("Plugins Path:", QLibraryInfo.location(QLibraryInfo.PluginsPath))
Plugins Path: C:/qt64/qt_1544645195969/_h_env/Library/plugins

发现路径为C:/qt64而实际上并没有这个文件夹。

手动检查路径配置:在目录 <python_env>\Library\plugins\platforms\ 中查看是否有 qwindows.dll 文件。
如果存在,则原因是 PyQt5 无法找到正确插件路径,故在代码开头手动设置 QT_PLUGIN_PATH,告诉 PyQt5 到正确路径加载插件:

import os
import sys

# 指定 Qt 插件路径
qt_plugin_path = os.path.join(sys.prefix, 'Library', 'plugins')
os.environ['QT_PLUGIN_PATH'] = qt_plugin_path
print("QT_PLUGIN_PATH:", os.environ['QT_PLUGIN_PATH'])

sys.prefix:返回当前 Python 解释器的基础安装路径。若使用的是虚拟环境,将指向虚拟环境的根目录。

也可用下面的方式直接指定插件路径:

import os
os.environ['QT_PLUGIN_PATH'] = r"D:\Anaconda\anaconda3\envs\text2human-cpu\Library\plugins"

更多推荐