使用PySide和QTextEdit的半透明高光

时间:2017-10-08 07:46:27

标签: python qt pyside alphablending 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)

1 个答案:

答案 0 :(得分:3)

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)的键来查找所需的“减去”颜色。)