import string
import sys
import traceback
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Main(QDialog):
    """定时器Demo"""
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
            self.init_slot()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.resize(480, 240)
            self.setWindowTitle("文本高亮demo")
            # 文本展示框
            self.plainTextEdit = QPlainTextEdit(self)
            self.plainTextEdit.setPlainText(string.ascii_letters)

            # 文本输入框
            self.lineEdit = QLineEdit(self)
            self.lineEdit.setPlaceholderText("请输入")

            # 布局
            layout = QVBoxLayout()
            layout.addWidget(self.plainTextEdit)
            layout.addWidget(self.lineEdit)

            self.setLayout(layout)
        except:
            traceback.print_exc()

    def init_slot(self):
        try:
            self.lineEdit.textChanged.connect(self.high_light)
        except:
            traceback.print_exc()

    def high_light(self):
        try:
            fmt = QTextCharFormat()
            fmt.setForeground(QColor("red"))

            text = self.lineEdit.text()
            self.plainTextEdit.moveCursor(QTextCursor.Start)  # 先把光标移动到开头
            while self.plainTextEdit.find(text):  # 查找所有文字
                cursor = self.plainTextEdit.textCursor()
                cursor.mergeCharFormat(fmt)
        except:
            traceback.print_exc()


if __name__ == '__main__':
    authorization = None
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
