Qt 和 opencv 应用程序无法在虚拟环境中运行

Qt and opencv app not working in virtual environment

我使用 pyqt5 和 opencv 创建了一个 GUI 应用程序。该应用程序在不激活虚拟环境的情况下工作正常,但是当我激活虚拟环境和 运行 该应用程序时,它显示此错误:

QObject::moveToThread: Current thread (0x125b2f0) is not the object's thread (0x189e780).
Cannot move to target thread (0x125b2f0)

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/deepak/Desktop/SampleApp/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, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl.

Aborted

我尝试了 运行 一个示例 pyqt5 代码(没有导入 opencv)和另一个代码(只使用 opencv)在虚拟环境中都运行良好。

操作系统:Parrot OS 4.11

Python版本:3.9.2

问题是opencv编译的Qt版本和PyQt5使用的版本不一样导致冲突

一个可能的解决方案是指明使用 PyQt5 使用的 Qt 插件。

import os
from pathlib import Path

import PyQt5
from PyQt5.QtWidgets import QWidget # others imports
import cv2

os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.fspath(
    Path(PyQt5.__file__).resolve().parent / "Qt5" / "plugins"
)
# ...

对于 PySide2:

import os
from pathlib import Path

import PySide2
from PySide2.QtWidgets import QWidget # others imports
import cv2

os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.fspath(
    Path(PySide2.__file__).resolve().parent / "Qt" / "plugins"
)
# ...

更新:

更好的选择是使用 QLibraryInfo 获取插件文件夹路径:

import os

from PyQt5.QtCore import QLibraryInfo
# from PySide2.QtCore import QLibraryInfo

import cv2

os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = QLibraryInfo.location(
    QLibraryInfo.PluginsPath
)

我通过降级cv2版本解决了这个问题,简单运行

python3 -m pip install opencv-contrib-python==4.1.0.25

我以前有 4.5.3.56