<kbd id="9plqc"><label id="9plqc"></label></kbd>

        <th id="9plqc"></th>
        1. <center id="9plqc"><video id="9plqc"></video></center>
          <sub id="9plqc"><form id="9plqc"><pre id="9plqc"></pre></form></sub>
          <nav id="9plqc"><form id="9plqc"><legend id="9plqc"></legend></form></nav>
          PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息 您所在的位置:網(wǎng)站首頁 屬龍男和屬鼠女婚配指數(shù)(shù)是多少 PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息

          PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息

          2025-07-18 13:50| 來源: 網(wǎng)絡(luò)整理| 查看: 265

          PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息

          本文演示 PyQt5 如何與 Python 的標(biāo)準(zhǔn)庫 Logging結(jié)合,然后輸出日志信息到如:QPlainTextEdit QTextBrowser上

          代碼結(jié)構(gòu)

          本文中全部代碼全在test_QPlainTextEdit_Log.py這一個文件中編碼,步驟中有變動的地方會注釋標(biāo)注,無改動的不會重復(fù)顯示出來,需要看完整代碼的,可直接移步到末尾。

          一. 創(chuàng)建測試頁面

          創(chuàng)建一個最簡單的窗口,其中的主要部件就是 QPlainTextEdit

          #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ @ File : test_QPlainTextEdit_Log.py @ Author : yqbao @ Version : V1.0.0 @ Description : """ import sys import logging from typing import Callable from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPlainTextEdit, QTextBrowser from PyQt5.QtCore import pyqtSignal, QObject class LogWindow(QWidget): """顯示日志的窗口""" def __init__(self): super().__init__() self.setWindowTitle("日志輸出") self.resize(600, 200) self.log = QPlainTextEdit(self) self.log.setReadOnly(True) # 設(shè)置為只讀模式 layout = QVBoxLayout() layout.addWidget(self.log) self.setLayout(layout) if __name__ == "__main__": app = QApplication(sys.argv) window = LogWindow() window.show() sys.exit(app.exec_())

          運行后,可以得到下面這樣的窗口 image

          二. 添加日志信號以及自定義處理器,并初始化日志

          這一步,就需要結(jié)合PyQt5的信號機制與Logging標(biāo)準(zhǔn)庫了,在初始化日式時,提供了三種處理器,其中最主要的就是 使用自定義的 QtHandler處理器,此處理器將把日志消息發(fā)送到對應(yīng)的 Qt部件,如這里的 QPlainTextEdit

          #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ @ File : test_QPlainTextEdit_Log.py @ Author : yqbao @ Version : V1.0.0 @ Description : """ class LogSignal(QObject): """日志信號""" log_signal = pyqtSignal(str) class QtHandler(logging.Handler): """日志處理器""" def __init__(self, signal): super().__init__() self.signal = signal def emit(self, record): log_entry = self.format(record) self.signal.log_signal.emit(log_entry) def init_log(update_log: Callable): """初始化日志系統(tǒng)""" log_signal = LogSignal() log_signal.log_signal.connect(update_log) # 日志信號連接用于更新顯示的槽函數(shù) logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 創(chuàng)建文件處理器,將日志寫入文件(不需要可刪除) file_handler = logging.FileHandler('application.log', encoding="utf-8") # 文件處理器 file_handler.setLevel(logging.DEBUG) # 設(shè)置文件日志的級別 file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) logger.addHandler(file_handler) # 創(chuàng)建自定義處理器,就日志輸出到 Qt 頁面顯示 qt_handler = QtHandler(log_signal) # 使用自定義的日志處理器 qt_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logger.addHandler(qt_handler) # 控制臺輸出(不需要可刪除,刪除后控制臺將不在輸出日志信息,僅顯示 print 打印) stream_handler = logging.StreamHandler() # 輸出到控制臺 stream_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s ")) logger.addHandler(stream_handler) return logger class LogWindow(QWidget): """顯示日志的窗口""" ... # 忽略 無變化 三. 在顯示窗口中調(diào)用日志,用于顯示更新 #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ @ File : test_QPlainTextEdit_Log.py @ Author : yqbao @ Version : V1.0.0 @ Description : """ class LogWindow(QWidget): """顯示日志的窗口""" def __init__(self): super().__init__() ... # 忽略 self.logger = init_log(self.update_log) # 初始化日志 # 舉例 self.logger.info("這是一個消息") def update_log(self, log_text): self.log.append(log_text) # 更新 QPlainTextEdit 內(nèi)容 # 將光標(biāo)移動到文本的最后一行 cursor = self.log.textCursor() cursor.movePosition(cursor.End) # 移動光標(biāo)到最后 self.log.setTextCursor(cursor)

          運行后的效果如下: image

          四. 在其他方法或類中輸出消息 #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ @ Project : Qt5Examples @ File : test_QPlainTextEdit_Log.py @ Author : yqbao @ Version : V1.0.0 @ Description : """ def fun_logging(logger): """使用舉例:在方法中輸出日志""" logger.info("這是一個方法中的 INFO 消息") logger.warning("這是一個方法中的 WARNING 消息") logger.error("這是一個方法中的 ERROR 消息") class ClassLogging(object): """使用舉例:在類中輸出日志""" def __init__(self, logger): self.logger = logger def log_output(self): self.logger.info("這是一個類中的 INFO 消息") self.logger.warning("這是一個類中的 WARNING 消息") self.logger.error("這是一個類中的 ERROR 消息") class LogWindow(QWidget): """顯示日志的窗口""" def __init__(self): super().__init__() ... # 忽略 self.logger = init_log(self.update_log) # 初始化日志 # 舉例 self.logger.info("這是一個消息") # 舉例:在其他模塊中輸出日志 fun_logging(self.logger) log_example = ClassLogging(self.logger) log_example.log_output() def update_log(self, log_text): ... # 忽略 無變化

          運行后的效果如下: image

          五. 使用 QTextBrowser 或者 QTextEdit

          為啥要使用 QTextBrowser 或者 QTextEdit,如下:

          QPlainTextEdit適合顯示大量純文本的顯示,性能比QTextBrowser更強 QTextBrowser支持富文本(HTML、格式化文本等),可以顯示帶顏色、字體和其他格式的日志信息。但是文本是只讀的。 QTextEdit 支持富文本(HTML、格式化文本等),可以顯示帶顏色、字體和其他格式的日志信息。文本是可以編輯的

          舉例,修改成 QTextBrowser顯示,只需要修改兩句話:

          #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ @ Project : Qt5Examples @ File : test_QPlainTextEdit_Log.py @ Author : yqbao @ Version : V1.0.0 @ Description : """ class LogWindow(QWidget): """顯示日志的窗口""" def __init__(self): super().__init__() # self.log = QPlainTextEdit(self) self.log = QTextBrowser(self) # 改成這句 def update_log(self, log_text): # self.log.appendPlainText(log_text) # 更新 QPlainTextEdit 內(nèi)容 self.log.append(log_text) # 更新 QTextBrowser 內(nèi)容 六. 完整代碼

          完整代碼見:GitHub,Gitee

          本文章的原文地址 GitHub主頁

          本文來自博客園作者:星塵的博客,轉(zhuǎn)載請注明出處:https://www.cnblogs.com/yqbaowo/p/18608186



          【本文地址】

          公司簡介

          聯(lián)系我們

          今日新聞

          推薦新聞

          專題文章
            CopyRight 2018-2019 實驗室設(shè)備網(wǎng) 版權(quán)所有
            黄色免费网站在线看,韩国精品在线观看,韩国美女一区二区,99国产热 芜湖县| 上犹县| 临泽县| 潮安县| 凤阳县| 双峰县| 云南省| 托里县| 三江| 明星| 吴忠市| 理塘县| 犍为县| 新野县| 大安市| 巴楚县| 壤塘县| 永兴县| 平度市| 盘山县| 洱源县| 许昌县| 军事| 平潭县| 彰化市| 民权县| 陆川县| 宁海县| 清远市| 和静县| 南通市| 南木林县| 大安市| 开原市| 长海县| 湘乡市| 遂溪县| 富宁县| 延津县| 饶河县| 上饶县| http://444 http://444 http://444 http://444 http://444 http://444