如何将QLinearGradient指定为QTableView items background

2024-10-01 15:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

使用QLineEdit的调色板,我们可以将QGradient指定为其背景色:

line = QtGui.QLineEdit()
palette = line.palette()
QRectF = QtCore.QRectF(line.rect())
gradient = QtGui.QLinearGradient(QRectF.topLeft(), QRectF.topRight())
palette.setBrush(QtGui.QPalette.Base, QtGui.QBrush(gradient))
line.setPalette(palette)
line.show()

enter image description here

在处理QTableView及其QAbstractTableModel时,我从模型的data方法中为每个BackgroundColorRole返回一个实体QColor。我宁愿给tableView“item”指定渐变,而不是纯色。 如何指定渐变而不是纯色?在

enter image description here

^{pr2}$

Tags: rectlineqtguigradientpalette调色板背景色qtcore
1条回答
网友
1楼 · 发布于 2024-10-01 15:30:49

BackgroundRole用于生成一个QBrush,它可以有一个渐变。请参阅下面的示例。BackgroundColorRole似乎已过时,因此使用BackgroundRole可能更好,即使您不需要渐变。在

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

def create_gradient_brush():
    horGradient = QtGui.QLinearGradient(0, 0, 100, 0)
    verGradient = QtGui.QLinearGradient(0, 0, 0, 20)
    gradient = verGradient 
    gradient.setColorAt(0.0, QtGui.QColor("blue"))
    gradient.setColorAt(1.0, QtGui.QColor("red"))
    brush = QtGui.QBrush(gradient)
    return brush


class Model(QtCore.QAbstractTableModel):

    # The cell size is most likely unavailable in the model, it could be 
    # different per view, so we make a cell size-independent gradient.
    BG_BRUSH = create_gradient_brush()

    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

    def rowCount(self, parent=QtCore.QModelIndex()):
        return 3 
    def columnCount(self, parent=QtCore.QModelIndex()):
        return 3

    def data(self, index, role):
        if not index.isValid(): return 

        if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
            return self.items[index.row()][index.column()]

        if role == QtCore.Qt.ForegroundRole:
            return QtGui.QColor("white")

        # BackgroundColorRole is obsolete, use BackgroundRole, 
        # which returns a QBrush.
        if role == QtCore.Qt.BackgroundRole:
            return self.BG_BRUSH


def onClick(index):
    print 'clicked index:  %s'%index

tableModel=Model()
tableView=QtGui.QTableView() 
tableView.setModel(tableModel)
tableView.clicked.connect(onClick)

tableView.show()
app.exec_()

相关问题 更多 >

    热门问题