在QtextEdi中设置特定行的格式

2024-09-28 20:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

你如何在QTextEdit中选择一个特定的行并改变比如说。。。字体颜色变为绿色

我使用一个QTextEdit小部件来显示文件的内容,这是通过rs232发送的一系列命令。我想提供一些关于正在执行的行的视觉反馈,比如改变文本颜色。在

我可以更改附加到QTextEdit的文本文件(对于我显示的日志),但这不起作用。在

我一直在调查qcursor,但有点迷路了


Tags: 文本命令内容颜色部件rs232字体视觉
3条回答

最后我使用了光标:

    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)

我认为每次发生变化时,您都可以根据相关数据生成新的TextEdit内容。这应该很容易实现。QCursors和类似的东西对于可编辑的QTextEdit是很好的,但在您的例子中不是这样的。也不能保证它会更快。在

你会想使用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

示例:

^{pr2}$

或者一个简单的方法是从“\n”获取所有文本搜索行。在html/css标记中换行并重置文本。使用这种方法,您必须将所有内容更改为html,并确保格式正确(编辑器.toHtml()). 在

相关问题 更多 >