PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息 | 您所在的位置:網(wǎng)站首頁 › 屬龍男和屬鼠女婚配指數(shù)(shù)是多少 › PyQt5 使用 QPlainTextEdit/QTextBrowser 與 Logging 結(jié)合后顯示日志信息 |
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_())運行后,可以得到下面這樣的窗口
這一步,就需要結(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)運行后的效果如下:
運行后的效果如下:
為啥要使用 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 |
今日新聞 |
推薦新聞 |
專題文章 |
CopyRight 2018-2019 實驗室設(shè)備網(wǎng) 版權(quán)所有 |