Qt 访问 ExtraSelection 格式化(测试)

Qt accessing ExtraSelection formatting (testing)

我正在尝试测试我的 highlight_word 功能(如下)。但是,我不知道如何访问格式。我基本上只是想表明它是非默认的。我试过QPlainTextEdit.extraSelections(),但它显然是指被破坏的对象。我也尝试过 QTextCursor.charFormat().background.color() 使用适当定位的光标,但只得到 rgbf(0,0,0,1).

    def highlight_word(self, cursor: QTextCursor):
        selection = QTextEdit.ExtraSelection()
        color = QColor(Qt.yellow).lighter()
        selection.format.setBackground(color)
        selection.cursor = cursor
        self.setExtraSelections([selection])

更新

首先,我使用的是 PySide2,如果这会影响后面的内容。

接受的解决方案有效。我的问题是我正在写 self.editor.extraSelections()[0].format.background().color().getRgb(),这导致了 RuntimeError: Internal C++ object (PySide2.QtGui.QTextCharFormat) already deleted.。这让我觉得很奇怪。

QTextCursor.charFormat().background().color() 没有返回颜色是因为 QTextCharFormat 应用于 QTextEdit.ExtraSelection。您可以添加行 selection.cursor.setCharFormat(selection.format),但这不是必需的。如果您只是从 extraSelections() 访问选择并获取选择格式,它应该可以工作。

这里有一个例子,高亮一个词然后点击"Highlight"按钮,它会打印背景RGBA。点击"Get Selection"按钮后,会打印高亮字和背景色。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Template(QWidget):

    def __init__(self):
        super().__init__()
        self.textbox = QPlainTextEdit()
        btn = QPushButton('Highlight')
        btn.clicked.connect(self.highlight_word)
        btn2 = QPushButton('Get Selection')
        btn2.clicked.connect(self.get_selections)
        grid = QGridLayout(self)
        grid.addWidget(btn, 0, 0)
        grid.addWidget(btn2, 0, 1)
        grid.addWidget(self.textbox, 1, 0, 1, 2)

    def highlight_word(self):
        selection = QTextEdit.ExtraSelection()
        color = QColor(Qt.yellow).lighter()
        selection.format.setBackground(color)
        selection.cursor = self.textbox.textCursor()
        self.textbox.setExtraSelections([selection])
        print(selection.format.background().color().getRgb())

    def get_selections(self):
        selection = self.textbox.extraSelections()[0]
        print(selection.cursor.selectedText(), selection.format.background().color().getRgb())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = Template()
    gui.show()
    sys.exit(app.exec_())