我创建了一个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:我这里没有尝试实现的一件事是去除高光。如果您使用了相对较少的颜色集,我想您可以预先计算所有颜色组合的表,然后使用(current_color, removed_color)键查找所需的“减法”颜色)。

08-20 00:08