(PyQt)如何重置整个QTextEdit的CharFormat?
问题描述:
我在我的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(),但这似乎是没做什么。
答
应用新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)
真棒!我不知道光标只有一个.select(),不知何故在文档中错过了。 – Ajv2324