使用 PySide2 在 QTableView 中设置文本样式

2024-03-23

我有一个 QTableView 填充了正确的模型。 我想根据上下文更改文本的样式:

文本,如果括号之间有内容,则这部分文本应更改为绿色(包括括号)(并且粗体,只要它不难)。

如果您可以提供一个片段或超级简单的示例,我将不胜感激。


您必须使用一个委托来使用QTextDocument:

import random
from PySide2 import QtCore, QtGui, QtWidgets

words = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Mauris euismod cursus mi sit amet pellentesque. 
Proin sed lectus sed augue scelerisque congue eget quis leo. 
Curabitur ultrices nisi nisi, placerat gravida urna sagittis et. 
Nullam vitae urna tortor. Curabitur a lobortis metus, et laoreet arcu. 
Quisque a mi in purus molestie porta non sit amet purus. 
Sed porta non purus et suscipit.'''.split()

class HighlightDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None):
        super(HighlightDelegate, self).__init__(parent)
        self.doc = QtGui.QTextDocument(self)
        self._regex = QtCore.QRegularExpression()
        self._highlight_format = QtGui.QTextCharFormat()

    def paint(self, painter, option, index):
        painter.save()
        options = QtWidgets.QStyleOptionViewItem(option)
        self.initStyleOption(options, index)
        self.doc.setPlainText(options.text)
        self.apply_highlight()
        options.text = ""
        style = QtWidgets.QApplication.style() if options.widget is None \
            else options.widget.style()
        style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
        if option.state & QtWidgets.QStyle.State_Selected:
            ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
                QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
        else:
            ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
                QtGui.QPalette.Active, QtGui.QPalette.Text))

        textRect = style.subElementRect(
            QtWidgets.QStyle.SE_ItemViewItemText, options)

        if index.column() != 0:
            textRect.adjust(5, 0, 0, 0)

        the_constant = 4
        margin = (option.rect.height() - options.fontMetrics.height()) // 2
        margin = margin - the_constant
        textRect.setTop(textRect.top() + margin)

        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        self.doc.documentLayout().draw(painter, ctx)

        painter.restore()

    def apply_highlight(self):
        cursor = QtGui.QTextCursor(self.doc)
        cursor.beginEditBlock()
        highlightCursor = QtGui.QTextCursor(self.doc)
        while not highlightCursor.isNull() and not highlightCursor.atEnd():
            highlightCursor = self.doc.find(self.regex, highlightCursor)
            if not highlightCursor.isNull():
                highlightCursor.mergeCharFormat(self.highlightFormat)
        cursor.endEditBlock()

    @property
    def regex(self):
        return self._regex

    @regex.setter
    def regex(self, regex):
        if self._regex == regex: return
        self._regex = regex

    @property
    def highlightFormat(self):
        return self._highlight_format

    @highlightFormat.setter
    def highlightFormat(self, fmt):
        self._highlight_format = fmt

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.table = QtWidgets.QTableView()

        self._delegate = HighlightDelegate(self.table)
        self._delegate.regex = QtCore.QRegularExpression(r"\(.*?\)")
        fmt = QtGui.QTextCharFormat()
        fmt.setForeground(QtCore.Qt.green)
        fmt.setFontWeight(QtGui.QFont.Bold)
        self._delegate.highlightFormat = fmt
        self.table.setItemDelegate(self._delegate)

        model = QtGui.QStandardItemModel(10, 4)
        for i in range(model.rowCount()):
            for j in range(model.columnCount()):
                item = QtGui.QStandardItem("{}({}){}".format(*random.sample(words,3)))
                model.setItem(i, j, item)
        self.table.setModel(model)
        self.setCentralWidget(self.table)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PySide2 在 QTableView 中设置文本样式 的相关文章

  • Flask:缓存静态文件(.js、.css)

    我真的找不到任何这方面的资源 那么如何将视图 函数的缓存与静态文件 即 css js 分开 我想将静态对象缓存一周 另一方面 我只需要缓存函数 视图几分钟 当我执行以下操作时 from flask ext cache import Cach
  • 删除 python vaex 中的重复行

    我正在使用 python vaex 但我不知道如何删除数据框中的重复行 例如 在 pandas 中存在以下方法drop duplicates vaex中有没有类似的功能 似乎还没有 但我们应该在某个时候期待这个功能 其间 有vaex创始人的
  • 将 SQLite 的 FTS3/4 与 Python 3 结合使用

    我一直在使用 python 的 Flask 框架开发 peewee 的示例博客应用程序 看https github com coleifer peewee https github com coleifer peewee 内部示例 gt 博
  • Python 包?

    好吧 我认为无论我做错了什么 它可能都是显而易见的 但我无法弄清楚 我已经阅读并重新阅读了有关包的教程部分 我唯一能想到的是这不起作用 因为我直接执行它 这是目录设置 eulerproject init py euler1 py euler
  • Ttk Treeview:跟踪键盘选择

    这是一个带有 ttk 树视图的 Tk 小部件 当用户单击该行时 会执行某些功能 此处仅打印项目文本 我需要的是以下内容 最初的重点是文本输入 当用户按下 Tab 键时 焦点应该转到第一行 并且应该执行绑定到 Click 事件的函数 当用户使
  • Python Subversion 包装器库

    在颠覆的文档 http svnbook red bean com en 1 7 svn developer usingapi html svn developer usingapi otherlangs有一个从 Python 使用 Subv
  • set() 可以在 Python 进程之间共享吗?

    我正在 Python 2 7 中使用多重处理来处理非常大的数据集 当每个进程运行时 它会将整数添加到共享的 mp Manager Queue 中 但前提是其他进程尚未添加相同的整数 由于您无法对队列进行 in 式成员资格测试 因此我这样做的
  • BeautifulSoup 抓取街道地址

    我正在使用最底部的代码来获取weblink 以及清真寺名称 不过我也想得到面值 and 街道地址 请帮助我被困住了 目前我得到以下信息 Weblink div class subtitleLink a href http www salat
  • 散景服务器获取鼠标位置

    我正在开发一个带有散景 0 12 2 的交互式应用程序 它根据特定的交互更新绘图 现在 我使用滑块来更改图中字形的位置 但实际上我想访问鼠标在特定图中的位置 数据集是一个多维矩阵 张量 密集数据 每个图在特定位置显示一个维度 如果我更改一个
  • Python Pandas groupby、排名,然后根据自定义排名分配值

    问题设置 大熊猫数据框 df pd DataFrame Group A A A A A A A A A Subgroup Group 1 Group 1 Group 1 Group 1 Group 1 Group 1 Group 2 Gro
  • 为线条指定颜色

    我试图在 matplotlib 中绘制可变数量的行 其中 X Y 数据和颜色存储在 numpy 数组中 如下所示 有没有办法将颜色数组传递到绘图函数中 这样我就不必采取额外的步骤来单独为每条线分配颜色 我是否应该将 RGB 颜色数组转换为另
  • 无法运行特定的 .pyc 文件

    使用编译在unix工作的python文件后 import py compile py compile compile server py 我在同一目录中获得 pyc 文件 但是当我尝试在 putty 中使用 server pyc 运行该文件
  • 在 Mac OS x 10.7.5 中运行 Scrapy 所需的文件,使用 Python 2.7.3 IEPD_free(32 位)

    我是第一次测试 scrapy 使用命令安装后 sudo easy install U scrapy 一切似乎都运行正常 但是 当我运行时 scrapy startproject tutorial 我得到以下信息 luismacbookpro
  • 使用来自不同线程的实时数据更新 QTableView 的最佳策略

    我的应用程序现在启动几个线程 如 5 10 个 来从不同源收集数据 它们与主 GUI 线程分离 因此我在 GUI 中感觉不到任何缓慢 并且我可以在后台线程工作时继续工作 一切都很棒 但现在我希望能够在我的主 GUI 中的 QTableVie
  • numpy 中的分层抽样

    在 numpy 中我有一个这样的数据集 前两列是索引 我可以通过索引将数据集分成多个块 即第一个块是 0 0 第二个块是 0 1 第三个块 0 2 然后是 1 0 1 1 1 2 等等 每个块至少有两个元素 索引列中的数字可能会有所不同 我
  • 按工作日分组的熊猫 (M/T/W/T/F/S/S)

    我有一个 pandas 数据框 其中包含 YYYY MM DD arrival date 形式的时间序列 作为索引 我想按每个工作日 周一到周日 进行分组 以便计算其他日期列是平均值 中位数 标准差等 我最终应该只有七行 到目前为止我只知道
  • Python 中的数据可用性图表

    我想知道Python是否有一些东西可以绘制具有多个变量的时间序列的数据可用性 下面显示了一个示例 取自Visavail js 时间数据可用性图表 https github com flrs visavail 1 description 以下
  • PyTorch 中的交叉熵

    交叉熵公式 但为什么下面给出loss 0 7437代替loss 0 since 1 log 1 0 import torch import torch nn as nn from torch autograd import Variable
  • Pygame 文本不渲染

    好的 我正在用 python 和 pygame 制作一个多项选择测验游戏 不过 我已经完成了开始屏幕并尝试制作问题屏幕 我根本不明白为什么文本不呈现 这是我的代码 enter pressed False random question ra
  • 如何从 Python 脚本捕获 Curl 的输出

    我想使用curl查找有关网页的信息 但在Python中 到目前为止我有这个 os system curl head www google com 如果我运行它 它会打印出 HTTP 1 1 200 OK Date Sun 15 Apr 20

随机推荐