如何使用setFormats**?**
该程序在QTextEdit中以QMainWindow显示。
任务是找到“导入”一词,并使用block.layout.setFormats在红色中突出显示它(我不希望撤销-重做历史包含外观更改,也不想使用QSyntaxHighlighter)。
我不明白为什么当找到“导入”然后是setFormats这个词时,相应的块变得不可见。
from PySide6 import QtWidgets, QtCore, QtGui
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.central_widget = QtWidgets.QWidget(self)
self.central_widget.setLayout(QtWidgets.QVBoxLayout(self.central_widget))
self.text_editor = QtWidgets.QTextEdit(self.central_widget)
self.central_widget.layout().addWidget(self.text_editor)
self.setCentralWidget(self.central_widget)
self.text_editor.setFont(QtGui.QFont('Arial', 14))
self.text_editor.textChanged.connect(self.text_changed)
@QtCore.Slot()
def text_changed(self):
word = 'import'
text_cursor_before_find_op = self.text_editor.textCursor()
self.text_editor.moveCursor(QtGui.QTextCursor.MoveOperation.Start)
found = self.text_editor.find(word)
if found:
text_cursor = self.text_editor.textCursor()
text_cursor.setPosition(text_cursor.position())
block = text_cursor.block()
position_in_block = text_cursor.positionInBlock() - len(word)
format_range = QtGui.QTextLayout.FormatRange()
format_range.start = position_in_block
format_range.length = len(word)
format_range.format = self.text_editor.currentCharFormat()
format_range.format.setForeground(QtGui.QColor('#FF0000'))
formats = [format_range]
block.layout().setFormats(formats)
print(position_in_block,
repr(block.text()),
(format_range.start, format_range.length, format_range.format),
block.isValid(), block.isVisible(),
sep='\n', end='\n\n')
self.text_editor.setTextCursor(text_cursor_before_find_op)
app = QtWidgets.QApplication()
window = MainWindow()
window.show()
app.exec()发布于 2022-07-03 18:54:26
我不知道为什么block.layout.setFormats()不工作。
但是,如果您的意图是突出显示“导入”一词,那么您可能需要使用类似的内容。
from PySide6 import QtWidgets, QtCore, QtGui
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.central_widget = QtWidgets.QWidget(self)
self.central_widget.setLayout(QtWidgets.QVBoxLayout(self.central_widget))
self.text_editor = QtWidgets.QTextEdit(self.central_widget)
self.central_widget.layout().addWidget(self.text_editor)
self.setCentralWidget(self.central_widget)
self.text_editor.setFont(QtGui.QFont('Arial', 14))
self.text_editor.textChanged.connect(self.text_changed)
@QtCore.Slot()
def text_changed(self):
word = 'import'
text_cursor = self.text_editor.document().find(word)
if text_cursor:
extraSelection = QtWidgets.QTextEdit.ExtraSelection()
extraSelection.cursor = text_cursor
extraSelection.format = self.text_editor.currentCharFormat()
extraSelection.format.setForeground(QtGui.QColor('#FF0000'))
self.text_editor.setExtraSelections([extraSelection])
else:
self.text_editor.setExtraSelections([])
app = QtWidgets.QApplication()
window = MainWindow()
window.show()
app.exec()当然,这也有一些局限性,例如,只在整个文档中找到第一次出现,不检查单词是否由空格分隔,在将单词更改为其他内容后保持格式等等。但是,您需要自己解决这些问题。你的原装也会有同样的限制。
https://stackoverflow.com/questions/72847914
复制相似问题