You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySide6 QFileSystemModel在Windows下中文路径读取失败求助

解决PySide6+OpenCV在Windows下中文路径乱码问题

问题现象

使用PySide6开发文件管理器,通过QFileSystemModel和QSortFilterProxyModel获取文件路径时,MacOS下可正常通过OpenCV读取含中文路径的图片;但Windows系统中路径会出现乱码(例如C:/Users/Moon/OneDrive/µûçµíú/σ╖ÑΣ╜£/code/python/test/Σ╜áσÑ╜.png),导致cv2.imread返回None,触发AttributeError。

问题原因

Windows系统中,Qt文件路径API的字符串编码与Python/OpenCV存在兼容性差异:尽管Python默认使用UTF-8,但Qt在Windows下可能将本地编码(GBK)的路径错误转换,同时OpenCV的imread对Windows中文路径的原生支持不足,无法解析乱码路径。

解决方案

方案1:用Qt读取文件内容后传给OpenCV(跨平台推荐)

绕过路径传递环节,直接用Qt的QFile读取文件二进制内容,再通过OpenCV的imdecode解析,彻底避免路径编码问题。

修改tree_response函数:

import numpy as np

@Slot()
def tree_response(self, selected: QtCore.QItemSelection, deselected: QtCore.QItemSelection):
    file_path = self.get_current_path()
    # 用QFile读取文件二进制数据
    q_file = QtCore.QFile(file_path)
    if q_file.open(QtCore.QIODevice.ReadOnly):
        raw_data = q_file.readAll()
        # 转换为numpy数组并解码
        buf = np.frombuffer(raw_data.data(), np.uint8)
        img = cv2.imdecode(buf, cv2.IMREAD_COLOR)
        if img is not None:
            print(img.shape)
            print(file_path)
        else:
            print("图片解码失败")
    else:
        print(f"无法打开文件: {file_path}")

方案2:转换为Windows长路径格式

给Windows路径添加\\?\前缀,强制系统使用Unicode路径解析,避免编码转换错误。

修改get_current_path函数:

import os

def get_current_path(self):
    index = self.tree_view.currentIndex()
    source_index = self.sort_proxy_model.mapToSource(index)
    file_path = self.model.filePath(source_index)
    
    # 仅针对Windows系统处理
    if os.name == 'nt':
        file_path = os.path.abspath(file_path)
        # 转换为长路径格式
        if not file_path.startswith('\\\\?\\'):
            file_path = f'\\\\?\\{file_path.replace("/", "\\")}'
    return file_path

方案3:直接获取Unicode格式路径

从QFileSystemModel直接获取QFileInfo对象,提取原生Unicode路径,避免中间编码转换。

修改get_current_path函数:

def get_current_path(self):
    index = self.tree_view.currentIndex()
    source_index = self.sort_proxy_model.mapToSource(index)
    # 直接从模型获取QFileInfo
    file_info = self.model.fileInfo(source_index)
    # 获取Unicode格式的绝对路径
    file_path = file_info.absoluteFilePath()
    return file_path

验证说明

  • 方案1完全绕开路径编码问题,Mac和Windows平台均适用
  • 方案2仅针对Windows系统,需注意路径格式转换的正确性
  • 方案3优化Qt路径获取逻辑,部分场景下可直接解决乱码问题

内容的提问来源于stack exchange,提问作者Frank Mouzrt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:43:17