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

Python读取UTF-8编码文件仍显示乱码的Qt界面问题求助

Qt TextView组件读取UTF-8文件点击链接后乱码问题

我用Python开发Qt的TextView组件时遇到以下问题:直接读取单个UTF-8编码的TXT文件显示正常,但点击文件夹生成的文件链接后,文本会出现乱码。

尝试过两种解决方式均无效:

  • 使用chardet的detect_encoding函数检测文件编码,但该函数的打印语句无任何终端输出;
  • 直接指定UTF-8编码读取文件。

已确认原TXT文件确实为UTF-8编码。

相关代码

import os
import chardet
from PyQt5 import QtWidgets, QtCore

class TextView(QtWidgets.QWidget):

    def set_text(self, file_path):
        if os.path.isfile(file_path):  # 路径指向单个文件时逻辑正常
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    text_content = f.read()
                    self.text.setText(text_content)
            except Exception as e:
                print(e)
        elif os.path.isdir(file_path):  # 路径指向文件夹
            file_list_html = []
            file_list = os.listdir(file_path)
            for file in file_list:  
                file_path_full = os.path.join(file_path, file)  
                if file.endswith(".txt") and os.path.isfile(file_path_full):
                    file_list_html.append(f"<a href='{file_path_full}'>{file}</a>")  
                    # 列表生成正常,但点击链接后文本乱码
            file_list_str = "<br>".join(file_list_html)
            self.text.setOpenExternalLinks(True)
            self.text.setHtml(file_list_str)
            self.text.anchorClicked.connect(self.open_link)
        else:
            print(f"{file_path} 不是文件或目录")

    def open_link(self, url):
        file_path = QtCore.QUrl.toLocalFile(url)
        if file_path.endswith(".txt"):
            try:
                # encoding = self.detect_encoding(file_path)
                # print(encoding)  
                # 异常:该行打印无终端输出
                with open(file_path, "r", encoding="UTF-8") as f:
                    text_content = f.read()
                    self.text.setText(text_content)
            except Exception as e:
                print(e)

    def detect_encoding(self, file_path):  # 注:原代码缺少self参数,已修正
        try:
            with open(file_path, "rb") as f:
                rawdata = f.read()
                result = chardet.detect(rawdata)
                print(result['encoding'])
                return result['encoding']
        except Exception as e:
            print(e)

相关截图

  • 文件夹文件列表显示:
    文件夹文件列表

  • 点击链接后乱码显示:
    点击链接后乱码

  • 原文件编码确认(UTF-8):
    原文件编码为UTF-8

内容的提问来源于stack exchange,提问作者ACTony 42

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:49:53