Python 突出显示QTextEdit文档上的行

Python 突出显示QTextEdit文档上的行,python,pyqt,pyqt5,highlight,qtextedit,Python,Pyqt,Pyqt5,Highlight,Qtextedit,试图创建一种使用PyQt5和Python3突出显示QTextEdit小部件文档中给定行号的方法。下面是尝试的代码,非常感谢stackoverflow中以前回答过类似问题的人: 从PyQt5.QtCore导入Qt、QTimer、QEventLoop 从PyQt5.QtGui导入QTextBlockFormat、QTextBlock、QTextCursor 从PyQt5.qtwidts导入QWidget、QApplication、QTextEdit、QVBoxLayout 样本= 测试文档。。。 这

试图创建一种使用PyQt5和Python3突出显示QTextEdit小部件文档中给定行号的方法。下面是尝试的代码,非常感谢stackoverflow中以前回答过类似问题的人:

从PyQt5.QtCore导入Qt、QTimer、QEventLoop 从PyQt5.QtGui导入QTextBlockFormat、QTextBlock、QTextCursor 从PyQt5.qtwidts导入QWidget、QApplication、QTextEdit、QVBoxLayout 样本= 测试文档。。。 这是2号线 这是3号线 说明: 这是一个解释部分。这里我们来解释一下。 解释部分结束。 返回到文档正文。 这是8号线。 这是最后一行。 类WindowQWidget: 定义初始自我: 超级窗口,自我初始化__ self.editor=QTextEditself self.editor.setTextsample self.format_normal=QTextBlockFormat self.format_normal.setBackgroundQt.white self.highlight_format=QTextBlockFormat self.highlight_format.setBackgroundQt.yellow self.cursor=self.editor.textCursor 布局=QVBoxLayoutself layout.addWidgetself.editor def setLineFormatself、行号、格式: 设置QTextEdit中给定行号的高亮显示 self.cursor.election self.cursor.selectQTextCursor.Document self.cursor.setBlockFormatself.format\u正常 self.cursor=QTextCursorself.editor.document.findBlockByNumberlineNumber self.cursor.setBlockFormatformat格式 def循环通过管路自身: 循环通过指定的行。 对于范围为2、8的ii: self.setlineformatiii,self.highlight\u格式 自我暂停1000 def pauseself,持续时间: 提供指定持续时间的暂停。 loop=QEventLoop QTimer.singleShotduration,loop.quit loop.exec_ 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 导入系统 app=QApplicationsys.argv 窗口 window.setgeometry500150300300 橱窗秀 window.cycle\u通过\u行 sys.exitapp.exec_ 问题:

为什么在重置高亮显示时不需要实例化新光标来选择整个文档,但当需要选择单行时,需要创建QTextCursor的新实例

有没有一种方法可以在不创建新实例的情况下选择一行

如果文档很长并且需要选择大量行,这种方法会产生内存问题吗

垃圾收集器可能会处理这个问题,但我只是想更好地了解幕后的细节

为什么在重置高亮显示时不需要实例化新光标来选择整个文档,但当需要选择单行时,需要创建QTextCursor的新实例

因为与选择行、字等不同,选择整个文档不需要特殊信息,因此从QTextEdit获得的任何QTextCursor更准确地说,从与QTextEdit关联的QTextDocument获得的任何QTextCursor都将允许您选择整个文档

有没有一种方法可以在不创建新实例的情况下选择一行

要选择线,QTextCursor必须具有特殊信息,例如线的起点和终点,因此必须基于QTextBlock构建QTextCursor

如果文档很长并且需要选择大量行,这种方法会产生内存问题吗

不,不会创建内存问题,因为在您的情况下,您将其分配给同一个对象,但我仍然更喜欢使用以下方法

在我的方法中,QTextCursor是局部变量,当方法完成执行时,这些变量将被消除


非常感谢你的澄清。
def setLineFormat(self, lineNumber, format):
    """ Sets the highlighting of a given line number in the QTextEdit"""
    cursor = self.editor.textCursor()
    cursor.select(QTextCursor.Document)
    cursor.setBlockFormat(self.format_normal)

cursor = QTextCursor(self.editor.document().findBlockByNumber(lineNumber)) cursor.setBlockFormat(format)