似乎不太可能
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)
查找所需的“减法”颜色)。