首页 > 解决方案 > Windows 和 Linux 上的 QPlainTextEdit 图形错误

问题描述

我正在编写一个简单的 GUI,它在 QPlainTextEdit 中显示实时更新日志。

这是我要传递给的处理程序logging.Logger.addHandler()

class QPlainTextEditLogger(logging.Handler):
    """Modified From: https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt"""

    def __init__(self, parent):
        super().__init__()
        self.widget = QPlainTextEdit()
        self.widget.setReadOnly(True)

    def emit(self, record):
        msg = self.format(record)
        self.widget.appendPlainText(msg)
        self.widget.moveCursor(QtGui.QTextCursor.End)

    def write(self, m):
        pass

它正确地将我正在寻找的日志条目发送到 QPlainTextEdit 元素,但是,无论平台(或合成启用/禁用)如何,都会存在一个图形故障。
这是该行为的视频:

https://i.imgur.com/DTUbfcM.mp4

除非我手动滚动框或调整拆分器的大小,否则这些行会被切成两半。

无论我是否在上面的代码片段中实现自动滚动,都会发生这种情况:

moveCursor(QtGui.QTextCursor.End)

这可能是什么原因造成的?

编辑:我试图用下面的例子重现这个,但我没有遇到同样的问题。我认为这可能是因为我QPlainTextEdit()在主窗口之外的原始代码中创建了?

import sys
import time

from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import QPlainTextEdit
from PyQt5.QtCore import QThread, pyqtSignal

class Worker(QThread):
    newLine = pyqtSignal(str)

    def __init__(self):
        super().__init__()
    
    def run(self):
        for x in range(300):
            self.newLine.emit(f"Testing a very long line so that the words will wrap and hopefully reproduce the issue Testing a very long line so that the words will wrap and hopefully reproduce the issue {x}")
            time.sleep(0.1)


class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.editor = QPlainTextEdit(self)
        self.editor.setReadOnly(True)

        self.button = QtWidgets.QPushButton(self)
        self.button.setText("Go for it")

        self.layout = QtWidgets.QFormLayout()
        self.layout.addChildWidget(self.editor)
        self.layout.addChildWidget(self.button)

        self.button.clicked.connect(self.start_button_pressed)
        self.setCentralWidget(self.editor)
        self.show()

    def add_line(self, msg: str):
        self.editor.appendPlainText(msg)

    def start_button_pressed(self):
        self.worker = Worker()
        self.worker.newLine.connect(self.add_line)
        self.worker.start()

app = QtWidgets.QApplication(sys.argv)
window = Window()
app.exec_()

标签: pythonpython-3.xpyqtpyqt5qplaintextedit

解决方案


推荐阅读