使用Matplotlib时出现Qt线程及xcb插件加载错误求助
报错信息
QObject::moveToThread: Current thread (0x831f000) is not the object's thread (0x95b40e0).
Cannot move to target thread (0x831f000)qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/me/miniconda3/envs/venv/lib/python3.9/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.Available platform plugins are: xcb, eglfs, minimal, minimalegl, offscreen, vnc, webgl.
Aborted (core dumped)
这个问题大多是Matplotlib依赖的Qt库和OpenCV自带的Qt插件冲突,或是系统缺少xcb相关底层依赖导致的,试试下面的解决办法:
方法1:切换Matplotlib后端,避开Qt
Matplotlib默认可能用Qt作为绘图后端,换成其他后端就能绕开Qt相关冲突:
- 临时修改(代码内生效):在导入Matplotlib前添加以下代码
import matplotlib # 用TkAgg作为交互式后端,不需要交互的话可以换成'Agg' matplotlib.use('TkAgg') import matplotlib.pyplot as plt
- 永久修改:找到Matplotlib的配置文件
matplotlibrc(路径可以用matplotlib.matplotlib_fname()查看),把backend一行改成backend: TkAgg或者backend: Agg。
方法2:解决OpenCV与Qt的路径冲突
报错里明确提到了cv2的Qt插件目录,强制系统优先使用系统自带的Qt插件即可:
- 终端运行脚本前设置环境变量:
export QT_QPA_PLATFORM_PLUGIN_PATH=/usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/
- 代码内设置环境变量:在代码最开头添加
import os # 路径根据自己系统的Qt插件位置调整,上面是Ubuntu/Debian的默认路径 os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = '/usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/'
- 或者直接安装无Qt依赖的OpenCV版本:
pip uninstall opencv-python pip install opencv-python-headless
方法3:安装缺失的系统底层依赖
xcb插件需要一些系统库支持,执行对应系统的安装命令:
- Debian/Ubuntu系:
sudo apt-get install libxcb-xinerama0 libxcb-cursor0
- CentOS/RHEL系:
sudo yum install libxcb-xinerama libxcb-cursor
内容的提问来源于stack exchange,提问作者DanielBell99

