2017-09-27 201 views
0

我在我的QTextEdit中的幾個單詞上使用了mergeCharFormat,以突出顯示它們。類似這樣的:(PyQt)如何重置整個QTextEdit的CharFormat?

import sys 
from PyQt4 import QtGui, uic 
from PyQt4.QtCore import * 

def drawGUI(): 
    app = QtGui.QApplication(sys.argv) 
    w = QtGui.QWidget() 
    w.setGeometry(200, 200, 200, 50) 
    editBox = QtGui.QTextEdit(w) 
    text = 'Hello stack overflow, this is a test and tish is a misspelled word' 
    editBox.setText(text) 

    """ Now there'd be a function that finds misspelled words """ 

    # Highlight misspelled words 
    misspelledWord = 'tish' 
    cursor = editBox.textCursor() 
    format_ = QtGui.QTextCharFormat() 
    format_.setBackground(QtGui.QBrush(QtGui.QColor("pink"))) 
    pattern = "\\b" + misspelledWord + "\\b" 
    regex = QRegExp(pattern) 
    index = regex.indexIn(editBox.toPlainText(), 0) 
    cursor.setPosition(index) 
    cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1) 
    cursor.mergeCharFormat(format_) 

    w.showFullScreen() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    drawGUI() 

所以,這個突出顯示的功能完全按照預期工作。但是,我無法找到一個清除textarea中亮點的好方法。什麼是做這種事情的好方法 - 基本上只是將整個QTextEdit的字符格式設置恢復爲默認值?

我到目前爲止所嘗試的是再次獲取光標,並將其格式設置爲具有清晰背景的新格式,然後將光標放在整個選區上並使用QTextCursor.setCharFormat(),但這似乎是沒做什麼。

回答

1

應用新QTextCharFormat整個文檔工作對我來說:

def drawGUI(): 
    ... 
    cursor.mergeCharFormat(format_) 

    def clear(): 
     cursor = editBox.textCursor() 
     cursor.select(QtGui.QTextCursor.Document) 
     cursor.setCharFormat(QtGui.QTextCharFormat()) 
     cursor.clearSelection() 
     editBox.setTextCursor(cursor) 

    button = QtGui.QPushButton('Clear') 
    button.clicked.connect(clear) 

    layout = QtGui.QVBoxLayout(w) 
    layout.addWidget(editBox) 
    layout.addWidget(button) 
+0

真棒!我不知道光標只有一個.select(),不知何故在文檔中錯過了。 – Ajv2324

相關問題