我想用下面这样的红色波浪在QTreeWidget中给一些东西下划线:

我试着用QTextCursor实现这一点,但显然这是不可能的。有人知道另一种方法吗?
举个例子,这里有一种用QTextCursor给单词加下划线的方法:
import sys
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, QtGui, uic
def drawGUI():
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
editBox = QtWidgets.QTextEdit(w)
text = 'THE_WORD'
editBox.setText(text)
cursor = editBox.textCursor()
format_ = QtGui.QTextCharFormat()
format_.setUnderlineStyle(QtGui.QTextCharFormat.WaveUnderline)
regex = QRegExp('\\bTHE_WORD\\b')
index = regex.indexIn(editBox.toPlainText(), 0)
cursor.setPosition(index)
cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
cursor.mergeCharFormat(format_)
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
drawGUI()发布于 2020-05-16 05:36:17
要做到这一点,可能有几种方法。一种方法是使用自定义委托。
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QApplication, QStyledItemDelegate
class CustomDelegate(QStyledItemDelegate):
def paint(self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex):
options = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(options, index)
if options.text != 'THE_WORD':
return super().paint(painter, option, index)
doc = QtGui.QTextDocument(options.text)
format_ = QtGui.QTextCharFormat()
format_.setUnderlineStyle(QtGui.QTextCharFormat.WaveUnderline)
format_.setUnderlineColor(QtCore.Qt.red)
cursor = doc.find(options.text)
cursor.movePosition(QtGui.QTextCursor.Start, QtGui.QTextCursor.MoveAnchor)
cursor.selectionStart()
cursor.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)
cursor.selectionEnd()
cursor.setCharFormat(format_)
painter.save()
painter.translate(option.rect.x(), option.rect.y())
doc.setDocumentMargin(0) # The text will be misaligned without this.
doc.drawContents(painter)
painter.restore()
app = QApplication(sys.argv)
w = QTreeWidget()
delegate = CustomDelegate(w)
w.setItemDelegate(delegate)
w.resize(300, 100)
w.setColumnCount(3)
w.addTopLevelItem(QTreeWidgetItem(['Foo', 'THE_WORD', 'Bar']))
w.show()
sys.exit(app.exec_())https://stackoverflow.com/questions/61822886
复制相似问题