Python (PyQt)如何重置整个QTextEdit的字符格式?
我在QTextEdit中的几个单词上使用mergeCharFormat,以突出显示它们。大概是这样的:Python (PyQt)如何重置整个QTextEdit的字符格式?,python,python-2.7,pyqt,formatting,qtextedit,Python,Python 2.7,Pyqt,Formatting,Qtextedit,我在QTextEdit中的几个单词上使用mergeCharFormat,以突出显示它们。大概是这样的: 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 = Q
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()
因此,此突出显示功能完全按照预期工作。但是,我找不到一个好方法来清除文本区域中的高光。做这件事的好方法是什么?本质上就是将整个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)
将新的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作为光标,但不知怎么的,文档中没有找到。