Qt正在访问ExtraSelection格式(测试)

问题描述 投票:0回答:1

我正在尝试测试我的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])

UPDATE

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

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

python pyqt pyside2
1个回答
1
投票

QTextCursor.charFormat().background().color()不返回颜色是因为QTextCharFormat被应用于QTextEdit.ExtraSelection。您可以添加行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_())
© www.soinside.com 2019 - 2024. All rights reserved.