请问在 PYQT5 的 QTextEdit 部件中如何高亮一部分文本(非整段文本)?

在查找实现这一目的的方法时,大多数找到的是QT的代码,或是简要描述继承QSyntaxHighlighter这个类然后就一笔带过,都没有具体的介绍如何实现高亮其中一部分的文本。
希望能有人指点一下这其中详细的过程,或是给我一个其他的方法来达到这个目的!
Jason990420
最佳答案
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QTextEdit, QVBoxLayout,
                             QPushButton)
def revise():
    html = ' '.join(('<p>This is', mark[mode], 'text with HTML</p>'))
    edit.setHtml(html)

def button_clicked():
    global mode
    mode = 1 - mode
    revise()

mode = 0
mark = ['not-highlight','<b>highlight</b>']

app = QApplication.instance()
if app is None:
    app = QApplication(sys.argv)

ui = QWidget()
ui.setWindowTitle('Example')
ui.resize(300, 100)

edit = QTextEdit()
button = QPushButton('Highlight')

layout = QVBoxLayout()
layout.addWidget(edit)
layout.addWidget(button)
ui.setLayout(layout)
button.clicked.connect(button_clicked)

revise()
ui.show()
sys.exit(app.exec_())

file

4年前 评论
讨论数量: 2

QTextEdit控件支持html文本,可以定义高亮的 参考这篇文章https://www.cnblogs.com/ygzhaof/p/10059283...

4年前 评论
Jason990420
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QTextEdit, QVBoxLayout,
                             QPushButton)
def revise():
    html = ' '.join(('<p>This is', mark[mode], 'text with HTML</p>'))
    edit.setHtml(html)

def button_clicked():
    global mode
    mode = 1 - mode
    revise()

mode = 0
mark = ['not-highlight','<b>highlight</b>']

app = QApplication.instance()
if app is None:
    app = QApplication(sys.argv)

ui = QWidget()
ui.setWindowTitle('Example')
ui.resize(300, 100)

edit = QTextEdit()
button = QPushButton('Highlight')

layout = QVBoxLayout()
layout.addWidget(edit)
layout.addWidget(button)
ui.setLayout(layout)
button.clicked.connect(button_clicked)

revise()
ui.show()
sys.exit(app.exec_())

file

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!