python - 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.
. 这让我觉得很奇怪。
解决方案
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_())
推荐阅读
- php - 注意:未定义索引 product_name
- angular - 从.net mvc api控制器下载角度应用程序中的文件时被CORS策略错误阻止
- laravel - 无法在后台使用 Laravel-snappy 生成 pdf
- python - Tkinter 输入未插入数据库(sqlite3)
- javascript - 如何按升序对 JavaScript 中的嵌套数组进行排序?
- angular - 在 PrimeNG p-table 中单击取消按钮后如何保留复选框的选择?
- android - 在 Visual Studio 中构建 cordova android apk 时出错
- python - 调用 QScreen.grabWindow() 时输入错误
- c# - 如何安装 Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms?
- c - C中的名称排序