PyQt5在curs下更改字体颜色

2024-09-28 21:58:46 发布

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

我正在尝试更改将突出显示的字体的颜色(红色)。我面临的问题是,只要我突出显示第一个单词,下面的所有文本都会变成红色。

def cursorPosition(self):
    logging.debug("Cursor Positiong changed")
    self.cursor = self.ui.captureWindow.textCursor()

    if self.cursor.hasSelection():
        fmt = QTextCharFormat()
        fmt.setForeground(Qt.red)

        logging.debug(self.cursor.selectedText())

        # We insert the new text, which will override the selected text
        self.cursor.insertText(self.cursor.selectedText(), fmt)
        # txt = '<p style="color:red;">' + self.cursor.selectedText() + '</p> '
        # self.cursor.insertHtml(txt)

        # And set the new cursor
        self.ui.captureWindow.setTextCursor(self.cursor)

我尝试了两种方法,insertTextinsertHtmlinsertHtml在结束标记后面有空格时起作用。去掉那个空格,它的行为和insertText一样,在第一次高亮显示之后,所有的东西都是红色的。你知道吗

enter image description here


Tags: thetextdebugselfuinewloggingred