2 回答
TA贡献1725条经验 获得超7个赞
必须考虑的重要事项QTextCursor.charFormat()
是:
返回光标position ( )之前字符的格式。
因此,这不仅不能很好地处理包含多种字符格式的选择,而且您还必须考虑光标位置,它可能会在选择中发生变化:它可能在开头(因此它会返回格式选择之前的字符)或结尾(返回选择中最后一个字符的格式)。
如果要根据当前光标位置反转状态(如果在开头,则使用第一个字符,如果在结尾,则使用最后一个),则可以使用以下内容:
TA贡献1827条经验 获得超7个赞
def toggle_italic_text(self):
cursor = self.textEdit.textCursor()
if not cursor.hasSelection():
charFormat = cursor.charFormat()
charFormat.setFontItalic(not charFormat.fontItalic())
cursor.setCharFormat(charFormat)
# in this case, the cursor has to be applied to the textEdit to ensure
# that the following typed characters use the new format
self.textEdit.setTextCursor(cursor)
return
start = cursor.selectionStart()
end = cursor.selectionEnd()
newCursor = QtGui.QTextCursor(self.textEdit.document())
newCursor.setPosition(start)
if cursor.position() == start:
cursor.setPosition(start + 1)
charFormat = cursor.charFormat()
charFormat.setFontItalic(not charFormat.fontItalic())
newCursor.setPosition(end, cursor.KeepAnchor)
newCursor.mergeCharFormat(charFormat)
如果要反转选择中的所有状态,则需要循环遍历所有字符。
虽然您可以只更改每个字符的 char 格式,但这对于非常大的选择来说并不是一件好事,因此解决方案是仅在 char 格式实际从以前的状态发生变化时应用斜体,并且在选择结束。
def toggle_italic_text(self):
# ...
start = cursor.selectionStart()
end = cursor.selectionEnd()
newCursor = QtGui.QTextCursor(self.textEdit.document())
newCursor.setPosition(start)
cursor.setPosition(start)
prevState = cursor.charFormat().fontItalic()
while cursor.position() < end:
cursor.movePosition(cursor.Right)
charFormat = cursor.charFormat()
if charFormat.fontItalic() != prevState or cursor.position() >= end:
newPos = cursor.position()
if cursor.position() < end:
newPos -= 1
newCursor.setPosition(newPos, cursor.KeepAnchor)
charFormat.setFontItalic(not prevState)
newCursor.mergeCharFormat(charFormat)
prevState = not prevState
newCursor.setPosition(cursor.position() - 1)
添加回答
举报