【问题标题】:Use a QTextCursor in a QTreeWidget in PyQt5在 PyQt5 的 QTreeWidget 中使用 QTextCursor
【发布时间】:2020-05-15 15:31:00
【问题描述】:

我想用这样的红色波浪在 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()

【问题讨论】:

  • 你如何实现你用 QTextCursor 显示的内容?

标签: python pyqt5 qtreewidget qtextcursor


【解决方案1】:

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

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_())

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2017-12-20
    • 2018-10-07
    • 2016-05-17
    • 2021-01-31
    • 2015-02-25
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多