在QtextEdit中格式化特定行

0 投票
3 回答
2672 浏览
提问于 2025-04-18 05:53

你想知道怎么在QTextEdit中选中某一行,并把那一行的字体颜色改成绿色。

我正在用QTextEdit这个小工具来显示一个文件的内容,这个文件里是通过rs232发送的一系列命令。我想给用户一些视觉上的反馈,比如说把正在执行的那一行的文字颜色改一下。

我能把一些文字加到QTextEdit里(我用它来显示日志),但是这并不能解决我想要的问题。

我查了一下QCursor,但有点搞不清楚。

3 个回答

0

你可以使用QTextDocument.findBlockByLineNumber()这个方法。当你找到一个块之后,可以简单地搜索"\n"来找到换行符的位置,然后用QTextBlock.firstLineNumber()来查看这一行的开始和结束位置。接着,你就可以修改这个块的QTextBlock.charFormat()。

def edit_line(editor, line_number):
    """Use the text cursor to select the given line number and change the formatting.

    ..note:: line number offsets may be incorrect

    Args:
        editor (QTextBrowser): QTextBrowser you want to edit
        line_num (int): Line number  you want to edit.
    """
    linenum = line_number - 1 
    block = editor.document().findBlockByLineNumber(linenum)
    diff = linenum - block.firstLineNumber()
    count = 0
    if diff == 0:
        line_len = len(block.text().split("\n")[0])
    else:
        # Probably don't need. Just in case a block has more than 1 line.
        line_len = 0
        for i, item in enumerate(block.text().split("\n")):
            # Find start
            if i + 1 == diff: # + for line offset. split starts 0
                count += 2 # \n
                line_len = len(item)
            else:
                count += len(item)

    loc = block.position() + count

    # Set the cursor to select the text
    cursor = editor.textCursor()

    cursor.setPosition(loc)
    cursor.movePosition(cursor.Right, cursor.KeepAnchor, line_len)

    charf = block.charFormat()
    charf.setFontUnderline(True) # Change formatting here
    cursor.setCharFormat(charf)
    # cursor.movePosition(cursor.Right, cursor.MoveAnchor, 1)
    # editor.setTextCursor(cursor)
# end edit_line

举个例子:

editor = QtGui.QTextEdit()
editor.setText("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n")

line_num = 6
edit_line(editor, line_num)

另外一种简单的方法是把所有文本抓取过来,然后从"\n"开始搜索这一行。接着把这一行用html/css标签包裹起来,再重置文本。用这种方法,你需要把所有内容都转换成html,并确保格式正确(editor.toHtml())。

1

我觉得你可以在每次有变化的时候,从相关的数据生成新的文本编辑内容。这应该很容易实现。QCursor之类的东西适合可编辑的QTextEdit,但在你的情况下并不适用。而且也不能保证这样做会更快。

0

我最后选择使用游标:

    self.script_cursor = QtGui.QTextCursor(self.scriptBuffer.document())
    self.scriptBuffer.setTextCursor(self.script_cursor)
    self.script_cursor.movePosition(QtGui.QTextCursor.Start)
    for i in range(data):
        self.script_cursor.movePosition(QtGui.QTextCursor.Down)

    self.script_cursor.movePosition(QtGui.QTextCursor.EndOfLine)
    self.script_cursor.movePosition(QtGui.QTextCursor.Start, QtGui.QTextCursor.KeepAnchor)
    tmp = self.script_cursor.blockFormat()
    tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
    self.script_cursor.setBlockFormat(tmp)

撰写回答