(七 美化-3)PyQT5 文本高亮与下划线

如下内容适用于 PyQT5。

1. 文本高亮

    cursor = self.textPassage.textCursor()
    # setup the desired format for matches
    format = QTextCharFormat()
    format.setBackground(QtGui.QBrush(QtGui.QColor("yellow")))
    format.setFontWeight(QFont.Bold)
    # setup the regex engine
    text_to_highlight = list_quest_sys_info[0]['QuestID'][-2:] # get Q3 From QuestID W011-Q3
    regex = QtCore.QRegExp(text_to_highlight)
    # process the text
    pos = 0
    index = regex.indexIn(self.textPassage.toPlainText(), pos)
    while (index != -1):
        # select the matched text and apply the desired format
        cursor.setPosition(index)
        cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
        cursor.mergeCharFormat(format)
        # move to the next match
        pos = index + regex.matchedLength()
        index = regex.indexIn(self.textPassage.toPlainText(), pos)

示例图如下:高亮对应题号


(七 美化-3)PyQT5 文本高亮与下划线_第1张图片
image.png

2. 表格内下划线

对表格内已经写入数据的 item 进行操作即可

    from PyQt5.QtGui import QFont
    for i in range(row_num):
        item = QtWidgets.QTableWidgetItem()
        self.tblQuestID.setItem(i, 0, item)
        item.setText(_translate("Dialog", list_sys_quest_id[i]["QuestID"]))
        underline = QFont()
        underline.setUnderline(True)
        item.setFont(underline)

3. html 文本下划线

首先要确认 tag 为
形式,不承认 [br] 形式。

    self.textPassage.setText(self.textPassage.toHtml())

示例图如下:

(七 美化-3)PyQT5 文本高亮与下划线_第2张图片
image.png

4. 文本内指定词汇间下划线

    cursor = self.textPassage.textCursor()
    # setup the desired format for matches
    underline_format = QTextCharFormat()
    underline_format.setFontWeight(QFont.Bold)
    underline_format.setFontUnderline(True)
    # set up the regex engine
    text_to_underline_1 = 'SUDL'
    text_to_underline_2 = 'EUDL'
    underline_regex_1 = QtCore.QRegExp(text_to_underline_1)
    underline_regex_2 = QtCore.QRegExp(text_to_underline_2)
    # process the text
    start_pos = 0
    end_pos = 0
    start_index = underline_regex_1.indexIn(self.textPassage.toPlainText(), start_pos)
    end_index = underline_regex_2.indexIn(self.textPassage.toPlainText(), end_pos)

    while (end_index != -1):
        # select the matched text and apply the desired format
        cursor.setPosition(start_index)
        cursor.movePosition(QtGui.QTextCursor.NextWord, 1)
        offset = end_index - start_index
        for i in range(offset+1):
            cursor.movePosition(QtGui.QTextCursor.NextCharacter, 1)
            cursor.mergeCharFormat(underline_format)
        # move to the next match
        start_pos = end_index + 1 #todo no +1 ?
        start_index = underline_regex_1.indexIn(self.textPassage.toPlainText(), start_pos)
        end_pos = end_index + 2
        end_index = underline_regex_2.indexIn(self.textPassage.toPlainText(), end_pos)

你可能感兴趣的:((七 美化-3)PyQT5 文本高亮与下划线)