[英]Use a QTextCursor in a QTreeWidget in PyQt5
我想用這樣的紅色波浪在 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()
可能有幾種方法可以做到這一點。 一種方法是使用自定義委托。
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_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.