Skip to main content
 首页 » 编程设计

python之如何选择 QTextBrowser 中的所有事件

2024年10月17日10yxwkf

代码创建了充满文本行的QTextBrowser 窗口。 我想选择所有匹配“Long Line”的词 如何实现?

from PyQt4 import QtCore, QtGui 
app = QtGui.QApplication([]) 
 
view = QtGui.QTextBrowser()  
for i in range(25): 
    view.append(10*('Long Line of text # %004d '%i) ) 
view.setLineWrapMode(0) 
 
view.find('Long Line') 
 
view.show() 
app.exec_() 

请您参考如下方法:

您可以使用 QTextEdit.setExtraSelections:

import sys 
from PyQt4.QtGui import (QApplication, QTextEdit, QTextBrowser, QTextCursor, 
                         QTextCharFormat, QPalette) 
 
app = QApplication(sys.argv) 
view = QTextBrowser() 
for i in range(25): 
    view.append(10*('Long Line of text # %004d '%i) ) 
view.setLineWrapMode(0) 
line_to_find = 'Long Line' 
 
# get default selection format from view's palette 
palette = view.palette() 
text_format = QTextCharFormat() 
text_format.setBackground(palette.brush(QPalette.Normal, QPalette.Highlight)) 
text_format.setForeground(palette.brush(QPalette.Normal, QPalette.HighlightedText)) 
 
# find all occurrences of the text 
doc = view.document() 
cur = QTextCursor() 
selections = [] 
while 1: 
    cur = doc.find(line_to_find, cur) 
    if cur.isNull(): 
        break 
    sel = QTextEdit.ExtraSelection() 
    sel.cursor = cur 
    sel.format = text_format 
    selections.append(sel) 
view.setExtraSelections(selections) 
 
view.show() 
app.exec_() 

结果如下:

或者尝试 QSyntaxHighlighter .