使用PySide和QTextEdit的半透明高亮

使用PySide和QTextEdit的半透明高亮

问题描述:

我创建了一个QTextEdit对象。以下代码为当前选定的文本添加了随机颜色的高光。我需要突出显示为半透明,所以我可以看到彼此重叠的突出显示。使用“setAlpha”似乎没有做任何事情。我如何设置突出显示的alpha值或以其他方式获取半透明度?使用PySide和QTextEdit的半透明高亮

# 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似乎不太可能支持像分层格式一样复杂的东西。所以我认为你将不得不自己混合颜色。下面的例子使用了一个相当粗糙的方法,但它似乎工作正常。我不完全相信你的目标是什么结果,但它应该给你一些想法如何proceeed:

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

+0

谢谢。您的代码解决了显示问题。我担心增加和删除亮点的复杂性。文本中的Alpha表示某种分层,是正确的?什么可以分层?除了textEdit之外,是否还有Qt小部件可以专门提供高亮层次? – davideps

+0

查找表就像它变得简单而高效。没有分层;只有背景画。我想图形框架提供了更多的可能性,但它似乎是一个像这样基本的重量级解决方案。 – ekhumoro

+0

我一直在努力让alpha工作。在QTextEdit窗口中,setAlpha似乎更像是一个饱和度设置,而不是真正的透明度。你的答案好像是镇上唯一的表演。谢谢。 – davideps