[英]Use a QTextCursor in a QTreeWidget in PyQt5
I would like to underline something in a QTreeWidget with a red wave like this:我想用这样的红色波浪在 QTreeWidget 中强调一些东西:
I tried to pull this off with a QTextCursor but apparently it's not possible.我试图用 QTextCursor 来解决这个问题,但显然这是不可能的。 Anyone knows another way?有人知道另一种方法吗?
As an exemple, here is a way to underline a word with 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()
There are probably several ways to accomplish this.可能有几种方法可以做到这一点。 One way is with a custom delegate.一种方法是使用自定义委托。
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.