You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyQt5中创建可无缝平铺的自定义对角线QBrush图案?

如何用QBrush和QPixmap绘制可无缝平铺的自定义粗细对角线图案?

最初我想使用渐变背景来突出QTableView中的特定单元格/项,但该方案未能成功实现。

随后我考虑通过CSS定义渐变背景,并利用Qt属性控制其显示对象,但问题在于QTableView的单元格/项为QStyledItemDelegate,正如Qt论坛帖子所述:

动态属性仅适用于QWidgets!

是否仅能对选中项应用该属性?
不行,无法直接实现。除非子类化自定义QStyledItemDelegate,并根据控件属性为绘制的索引初始化StyleOption。

之后我查阅QBrush文档,发现其支持多种图案,我喜欢Qt.BDiagPattern对角线图案/阴影线,但线条过细。

因此我想要自定义BDiagPattern的线条粗细,找到相关示例演示了如何绘制QPixmap并将其用作重复/平铺的纹理图案,但未展示对角线的实现方式。于是我编写了如下示例代码:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (Qt, QPointF, QEvent)
from PyQt5.QtGui import (QColor, QGradient, QLinearGradient, QBrush, QTransform)
from PyQt5.QtWidgets import QApplication

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data, parent):
        super(TableModel, self).__init__()
        self._data = data
        self.parent = parent
        self.bg_col1 = QColor("#A3A3FF")
        self.bg_col2 = QColor("#FFFFA3")
    
    def create_texture(self):
        pixmap = QtGui.QPixmap(QtCore.QSize(16, 16))
        pixmap.fill(QColor(0,0,0,0))
        painter = QtGui.QPainter()
        painter.begin(pixmap)
        painter.setPen(QtGui.QPen(self.bg_col1, 5, Qt.SolidLine))
        painter.drawLine(pixmap.rect().bottomLeft(), pixmap.rect().topRight())
        painter.end()
        return pixmap
    
    def data(self, index, role):
        if role == Qt.DisplayRole:
            return self._data[index.row()][index.column()]
        if role == Qt.BackgroundRole:
            if index.column() == 2:
                brush = QBrush(self.create_texture())
                brush.setTransform(QTransform(QTransform.fromScale(4, 4)))
                return brush
    
    def rowCount(self, index):
        return len(self._data)
    
    def columnCount(self, index):
        return len(self._data[0])

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.table = QtWidgets.QTableView()
        data = [
          [4, 9, 2, 2],
          [1, 0, 0, 0],
          [3, 5, 0, 0],
          [3, 3, 2, 2],
          [7, 8, 9, 9],
        ]
        self.model = TableModel(data, self)
        self.table.setModel(self.model)
        self.setCentralWidget(self.table)

app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

然而,输出中的对角线无法相互衔接——图案无法平铺。

那么,如何使用QBrush和QPixmap绘制带自定义线条粗细、可无缝平铺的对角线图案?


内容的提问来源于stack exchange,提问作者sdbbs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 22:14:57