| 48 | self.textEdit.setPlainText(text) |
| 49 | |
| 50 | def highlight(self): |
| 51 | text = self.findText.text() # 输入框中的文字 |
| 52 | if not text: |
| 53 | return |
| 54 | |
| 55 | col = QColorDialog.getColor(self.textEdit.textColor(), self) |
| 56 | if not col.isValid(): |
| 57 | return |
| 58 | |
| 59 | # 恢复默认的颜色 |
| 60 | cursor = self.textEdit.textCursor() |
| 61 | cursor.select(QTextCursor.Document) |
| 62 | cursor.setCharFormat(QTextCharFormat()) |
| 63 | cursor.clearSelection() |
| 64 | self.textEdit.setTextCursor(cursor) |
| 65 | |
| 66 | # 文字颜色 |
| 67 | fmt = QTextCharFormat() |
| 68 | fmt.setForeground(col) |
| 69 | |
| 70 | # 正则 |
| 71 | expression = QRegExp(text) |
| 72 | self.textEdit.moveCursor(QTextCursor.Start) |
| 73 | cursor = self.textEdit.textCursor() |
| 74 | |
| 75 | # 循环查找设置颜色 |
| 76 | pos = 0 |
| 77 | index = expression.indexIn(self.textEdit.toPlainText(), pos) |
| 78 | while index >= 0: |
| 79 | cursor.setPosition(index) |
| 80 | cursor.movePosition(QTextCursor.Right, |
| 81 | QTextCursor.KeepAnchor, len(text)) |
| 82 | cursor.mergeCharFormat(fmt) |
| 83 | pos = index + expression.matchedLength() |
| 84 | index = expression.indexIn(self.textEdit.toPlainText(), pos) |
| 85 | |
| 86 | |
| 87 | if __name__ == '__main__': |