为什么在使用 setCharFormat() 时出现 Stack Overflow 错误?
Why Do I get a Stack Overflow error when using setCharFormat()?
我正在编写一个方法 show_spelling_errors(),它循环遍历保存在列表 self.tokens 中的自定义对象,并使用每个对象的属性来更改 Qt TextEdit 中某些字体的颜色小部件。 show_spelling_errors() 由连接到 Qt 中的 textChanged 信号的另一个方法调用,因此只要用户在小部件中键入内容,它就会 运行。方法定义如下:
def show_spelling_errors(self):
try:
cursor = self.textEdit.textCursor()
incorrect_format = cursor.charFormat()
incorrect_format.setForeground(QtCore.Qt.GlobalColor.red)
for token in self.tokens:
if not token.is_spelled_correctly:
print("is spelled correctly: " + str(token.is_spelled_correctly))
cursor.movePosition(cursor.MoveOperation.Start, cursor.MoveMode.MoveAnchor)
cursor.movePosition(cursor.MoveOperation.NextWord, cursor.MoveMode.MoveAnchor, token.word_index)
cursor.movePosition(cursor.MoveOperation.EndOfWord, cursor.MoveMode.KeepAnchor)
print("selection start " + str(cursor.selectionStart()))
print("selection end " + str(cursor.selectionEnd()))
# cursor.setCharFormat(incorrect_format)
cursor.clearSelection()
如果我 运行 代码与上面完全一样,事情就会按预期进行。但是,如果我取消注释倒数第二行(实际上应该更改字体颜色),循环将不再终止,而是无限循环遍历 self.tokens 的第一个成员,然后最终导致堆栈溢出。我很困惑,在循环中包含这个语句会导致循环的行为(我认为应该是无关的?)以这种方式改变。
编辑:下面是重现此行为所需的代码
from PyQt6.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from PyQt6 import QtCore
import sys
import re
import traceback
from spellchecker import SpellChecker
class Token:
def __init__(self, chars, spell, start=0, word_index=0):
self.word_index = word_index
self.content = chars
self.token_length = len(chars)
self.start_pos = start
self.end_pos = start + self.token_length
self.is_spelled_correctly = len(spell.unknown([chars])) < 1
class TextEditDemo(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("QTextEdit")
self.resize(300, 270)
self.spell = SpellChecker()
self.textEdit = QTextEdit()
layout = QVBoxLayout()
layout.addWidget(self.textEdit)
self.setLayout(layout)
self.tokens = None
self.textEdit.textChanged.connect(self.handle_text)
def handle_text(self):
self.tokenize_text()
self.show_spelling_errors()
def show_spelling_errors(self):
try:
cursor = self.textEdit.textCursor()
incorrect_format = cursor.charFormat()
incorrect_format.setForeground(QtCore.Qt.GlobalColor.red)
for token in self.tokens:
if not token.is_spelled_correctly:
print("is spelled correctly: " + str(token.is_spelled_correctly))
cursor.movePosition(cursor.MoveOperation.Start, cursor.MoveMode.MoveAnchor)
cursor.movePosition(cursor.MoveOperation.NextWord, cursor.MoveMode.MoveAnchor, token.word_index)
cursor.movePosition(cursor.MoveOperation.EndOfWord, cursor.MoveMode.KeepAnchor)
print("selection start " + str(cursor.selectionStart()))
print("selection end " + str(cursor.selectionEnd()))
cursor.setCharFormat(incorrect_format)
cursor.clearSelection()
except:
traceback.print_exc()
def tokenize_text(self):
try:
print("tokenizing...")
text = self.textEdit.toPlainText()
text_seps = re.findall(' .', text)
current_pos = 0
start_positions = [current_pos]
for sep in text_seps:
current_pos = text.find(sep, current_pos) + 1
start_positions.append(current_pos)
self.tokens = [
Token(string, self.spell, start, word_ind) for
word_ind, (start, string) in
enumerate(zip(start_positions, text.split()))
]
except:
traceback.print_exc()
app = QApplication([])
win = TextEditDemo()
win.show()
sys.exit(app.exec())
解释:
如果您查看 textChanged
signal of QTextEdit
的文档:
void QTextEdit::textChanged() This signal is emitted whenever the
document's content changes; for example, when text is inserted or
deleted, or when formatting is applied.
Note: Notifier signal for property html. Notifier signal for property
markdown.
(强调我的)
表示格式改变时也会触发,从而产生死循环
解决方案:
一种可能的解决方案是使用 blockSignals 来阻止信号:
def handle_text(self):
self.textEdit.blockSignals(True)
self.tokenize_text()
self.show_spelling_errors()
self.textEdit.blockSignals(False)
但更优雅的解决方案是使用 QSyntaxHighlighter
:
来实现
import re
import sys
from functools import cached_property
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QSyntaxHighlighter, QTextCharFormat
from PyQt6.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from spellchecker import SpellChecker
class SpellSyntaxHighlighter(QSyntaxHighlighter):
WORD_REGEX = re.compile(
r"\b[^\d\W]+\b"
) #
@cached_property
def text_format(self):
fmt = QTextCharFormat()
fmt.setUnderlineColor(Qt.GlobalColor.red)
fmt.setUnderlineStyle(QTextCharFormat.UnderlineStyle.SpellCheckUnderline)
return fmt
@cached_property
def spellchecker(self):
return SpellChecker()
def highlightBlock(self, text):
misspelled_words = set()
for match in self.WORD_REGEX.finditer(text):
word = text[match.start() : match.end()]
if len(word) > 1 and self.spellchecker.unknown([word]):
misspelled_words.add(word)
for misspelled_word in misspelled_words:
for m in re.finditer(fr"\b{misspelled_word}\b", text):
self.setFormat(m.start(), m.end() - m.start(), self.text_format)
class TextEditDemo(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("QTextEdit")
self.resize(300, 270)
self.textEdit = QTextEdit()
layout = QVBoxLayout(self)
layout.addWidget(self.textEdit)
self.highlighter = SpellSyntaxHighlighter(self.textEdit.document())
def main():
app = QApplication([])
win = TextEditDemo()
win.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
我正在编写一个方法 show_spelling_errors(),它循环遍历保存在列表 self.tokens 中的自定义对象,并使用每个对象的属性来更改 Qt TextEdit 中某些字体的颜色小部件。 show_spelling_errors() 由连接到 Qt 中的 textChanged 信号的另一个方法调用,因此只要用户在小部件中键入内容,它就会 运行。方法定义如下:
def show_spelling_errors(self):
try:
cursor = self.textEdit.textCursor()
incorrect_format = cursor.charFormat()
incorrect_format.setForeground(QtCore.Qt.GlobalColor.red)
for token in self.tokens:
if not token.is_spelled_correctly:
print("is spelled correctly: " + str(token.is_spelled_correctly))
cursor.movePosition(cursor.MoveOperation.Start, cursor.MoveMode.MoveAnchor)
cursor.movePosition(cursor.MoveOperation.NextWord, cursor.MoveMode.MoveAnchor, token.word_index)
cursor.movePosition(cursor.MoveOperation.EndOfWord, cursor.MoveMode.KeepAnchor)
print("selection start " + str(cursor.selectionStart()))
print("selection end " + str(cursor.selectionEnd()))
# cursor.setCharFormat(incorrect_format)
cursor.clearSelection()
如果我 运行 代码与上面完全一样,事情就会按预期进行。但是,如果我取消注释倒数第二行(实际上应该更改字体颜色),循环将不再终止,而是无限循环遍历 self.tokens 的第一个成员,然后最终导致堆栈溢出。我很困惑,在循环中包含这个语句会导致循环的行为(我认为应该是无关的?)以这种方式改变。
编辑:下面是重现此行为所需的代码
from PyQt6.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from PyQt6 import QtCore
import sys
import re
import traceback
from spellchecker import SpellChecker
class Token:
def __init__(self, chars, spell, start=0, word_index=0):
self.word_index = word_index
self.content = chars
self.token_length = len(chars)
self.start_pos = start
self.end_pos = start + self.token_length
self.is_spelled_correctly = len(spell.unknown([chars])) < 1
class TextEditDemo(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("QTextEdit")
self.resize(300, 270)
self.spell = SpellChecker()
self.textEdit = QTextEdit()
layout = QVBoxLayout()
layout.addWidget(self.textEdit)
self.setLayout(layout)
self.tokens = None
self.textEdit.textChanged.connect(self.handle_text)
def handle_text(self):
self.tokenize_text()
self.show_spelling_errors()
def show_spelling_errors(self):
try:
cursor = self.textEdit.textCursor()
incorrect_format = cursor.charFormat()
incorrect_format.setForeground(QtCore.Qt.GlobalColor.red)
for token in self.tokens:
if not token.is_spelled_correctly:
print("is spelled correctly: " + str(token.is_spelled_correctly))
cursor.movePosition(cursor.MoveOperation.Start, cursor.MoveMode.MoveAnchor)
cursor.movePosition(cursor.MoveOperation.NextWord, cursor.MoveMode.MoveAnchor, token.word_index)
cursor.movePosition(cursor.MoveOperation.EndOfWord, cursor.MoveMode.KeepAnchor)
print("selection start " + str(cursor.selectionStart()))
print("selection end " + str(cursor.selectionEnd()))
cursor.setCharFormat(incorrect_format)
cursor.clearSelection()
except:
traceback.print_exc()
def tokenize_text(self):
try:
print("tokenizing...")
text = self.textEdit.toPlainText()
text_seps = re.findall(' .', text)
current_pos = 0
start_positions = [current_pos]
for sep in text_seps:
current_pos = text.find(sep, current_pos) + 1
start_positions.append(current_pos)
self.tokens = [
Token(string, self.spell, start, word_ind) for
word_ind, (start, string) in
enumerate(zip(start_positions, text.split()))
]
except:
traceback.print_exc()
app = QApplication([])
win = TextEditDemo()
win.show()
sys.exit(app.exec())
解释:
如果您查看 textChanged
signal of QTextEdit
的文档:
void QTextEdit::textChanged() This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied.
Note: Notifier signal for property html. Notifier signal for property markdown.
(强调我的)
表示格式改变时也会触发,从而产生死循环
解决方案:
一种可能的解决方案是使用 blockSignals 来阻止信号:
def handle_text(self):
self.textEdit.blockSignals(True)
self.tokenize_text()
self.show_spelling_errors()
self.textEdit.blockSignals(False)
但更优雅的解决方案是使用 QSyntaxHighlighter
:
import re
import sys
from functools import cached_property
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QSyntaxHighlighter, QTextCharFormat
from PyQt6.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from spellchecker import SpellChecker
class SpellSyntaxHighlighter(QSyntaxHighlighter):
WORD_REGEX = re.compile(
r"\b[^\d\W]+\b"
) #
@cached_property
def text_format(self):
fmt = QTextCharFormat()
fmt.setUnderlineColor(Qt.GlobalColor.red)
fmt.setUnderlineStyle(QTextCharFormat.UnderlineStyle.SpellCheckUnderline)
return fmt
@cached_property
def spellchecker(self):
return SpellChecker()
def highlightBlock(self, text):
misspelled_words = set()
for match in self.WORD_REGEX.finditer(text):
word = text[match.start() : match.end()]
if len(word) > 1 and self.spellchecker.unknown([word]):
misspelled_words.add(word)
for misspelled_word in misspelled_words:
for m in re.finditer(fr"\b{misspelled_word}\b", text):
self.setFormat(m.start(), m.end() - m.start(), self.text_format)
class TextEditDemo(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("QTextEdit")
self.resize(300, 270)
self.textEdit = QTextEdit()
layout = QVBoxLayout(self)
layout.addWidget(self.textEdit)
self.highlighter = SpellSyntaxHighlighter(self.textEdit.document())
def main():
app = QApplication([])
win = TextEditDemo()
win.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()