首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PyQt5的QTreeWidget中使用QTextCursor

在PyQt5的QTreeWidget中使用QTextCursor
EN

Stack Overflow用户
提问于 2020-05-15 23:31:00
回答 1查看 141关注 0票数 0

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

我试着用QTextCursor实现这一点,但显然这是不可能的。有人知道另一种方法吗?

举个例子,这里有一种用QTextCursor给单词加下划线的方法:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2020-05-16 05:36:17

要做到这一点,可能有几种方法。一种方法是使用自定义委托。

代码语言:javascript
复制
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_())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61822886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档