使用 PySide 和 QTextEdit 的半透明高亮

Semi-transparent highlights using PySide and QTextEdit

我创建了一个 QTextEdit 对象。下面的代码为当前选定的文本添加了随机颜色的突出显示。我需要高光是半透明的,这样我才能看到高光相互叠加。使用 "setAlpha" 似乎没有任何作用。如何为高光设置 alpha 或以其他方式获得半透明?

# Define cursor & span    
self.cursor = self.textdoc.textCursor()
self.selstart = self.cursor.selectionStart()
self.selend = self.cursor.selectionEnd()
self.seltext = self.cursor.selectedText()

# Create random color
r = randint(0,255)
g = randint(0, 255)
b = randint(0, 255)
color = QColor(r,g,b)
color.setAlpha(125)
format = QTextCharFormat()
format.setBackground(color)
self.cursor.setCharFormat(format)

QTextEdit 似乎不太可能支持像分层格式这样复杂的任何东西。所以我认为你必须自己混合颜色。下面的示例使用了一种相当粗糙的方法,但它似乎工作正常。我不太确定你的目标是什么结果,但它应该让你知道如何继续:

import sys
from random import sample
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Highlight', self)
        self.button.clicked.connect(self.handleButton)
        self.edit = QtGui.QTextEdit(self)
        self.edit.setText(open(__file__).read())
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)

    def blendColors(self, first, second, ratio=0.5, alpha=100):
        ratio2 = 1 - ratio
        return QtGui.QColor(
            (first.red() * ratio) + (second.red() * ratio2),
            (first.green() * ratio) + (second.green() * ratio2),
            (first.blue() * ratio) + (second.blue() * ratio2),
            alpha,
            )

    def handleButton(self):
        cursor = self.edit.textCursor()
        start = cursor.selectionStart()
        end = cursor.selectionEnd()
        if start != end:
            default = QtGui.QTextCharFormat().background().color()
            color = QtGui.QColor(*sample(range(0, 255), 3))
            color.setAlpha(100)
            for pos in range(start, end):
                cursor.setPosition(pos)
                cursor.movePosition(QtGui.QTextCursor.NextCharacter,
                                    QtGui.QTextCursor.KeepAnchor)
                charfmt = cursor.charFormat()
                current = charfmt.background().color()
                if current != default:
                    charfmt.setBackground(self.blendColors(current, color))
                else:
                    charfmt.setBackground(color)
                cursor.setCharFormat(charfmt)
            cursor.clearSelection()
            self.edit.setTextCursor(cursor)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(800, 100, 600, 500)
    window.show()
    sys.exit(app.exec_())

(PS: 我没有尝试在这里实现的一件事是 删除 高光。如果你使用相对较少的颜色集,我想你可以预先计算出所有颜色组合的table,然后使用(current_color, removed_color)的键查找所需的"subtracted"颜色)。