首页 > 解决方案 > Qt 访问 ExtraSelection 格式(测试)

问题描述

我正在尝试测试我的 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.. 这让我觉得很奇怪。

标签: pythonpyqtpyside2

解决方案


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

这里是一个例子,高亮一个词然后点击“高亮”按钮,它会打印背景RGBA。单击“获取选择”按钮后,它将打印突出显示的单词和背景颜色。

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_())

推荐阅读