Python PyQt5-更改光标下的字体颜色

Python PyQt5-更改光标下的字体颜色,python,pyqt5,qtextedit,qtextbrowser,qcursor,Python,Pyqt5,Qtextedit,Qtextbrowser,Qcursor,我正在尝试更改将高亮显示的字体的颜色(红色)。我面临的问题是,只要我突出显示第一个单词,以下所有文本都将变为红色。 def光标位置(自身): logging.debug(“光标位置已更改”) self.cursor=self.ui.captureWindow.textCursor() 如果self.cursor.hasSelection(): fmt=QTextCharFormat() fmt.设置前景(Qt.红色) logging.debug(self.cursor.selectedText(

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

def光标位置(自身):
logging.debug(“光标位置已更改”)
self.cursor=self.ui.captureWindow.textCursor()
如果self.cursor.hasSelection():
fmt=QTextCharFormat()
fmt.设置前景(Qt.红色)
logging.debug(self.cursor.selectedText())
#我们插入新文本,它将覆盖所选文本
self.cursor.insertText(self.cursor.selectedText(),fmt)
#txt='

'+self.cursor.selectedText()+'

' #self.cursor.insertHtml(txt) #并设置新光标 self.ui.captureWindow.setTextCursor(self.cursor)
我尝试了两种方法,
insertText
inserttml
insertHtml
在结束标记后有空格时起作用。删除该空格,其行为与插入文本的方式相同,在第一次高亮显示后,所有内容都将变为红色


您希望,如果某个单词上的光标高亮显示该单词,并且如果光标移动,则该单词不应再高亮显示。我是对的?是的。我突出显示一个单词,它的颜色应该只为该单词更改。它可以保持相同的颜色。但是这种颜色不应该像gif中显示的那样继续。应该高亮显示的单词是光标下的还是被按下的?我双击以高亮显示该单词。因此,根据定义,这将是一个被按下。我说得对吗?
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)