用不同的颜色填充QTreeView中的单元格,用不同的颜色填充QDiagCrossPattern

Fill cell in a QTreeView with a different color and QDiagCrossPattern with a different color

本文关键字:颜色 填充 QDiagCrossPattern QTreeView 单元格      更新时间:2023-10-16

我正在使用QTreeView,其中我希望特定单元格具有背景色,例如蓝色,并具有带有灰色的Qt::D iagCrossPattern。最好在 Model::d ata 而不是 paint 中使用此实现。有没有办法通过模型::D ata本身中的Qt::BackgroundRole来实现这一点?我试过这样做:

Model::data(const QModelIndex &index, int role) const
{
case Qt::BackgroundRole:
{
QColor backgroundcolor = Qt::blue; 
return QBrush(backgroundcolor, Qt::DiagCrossPattern);
}
}

但这可以使背景颜色保持透明,并且对角图案线为蓝色,这不是必需的。

您可以创建一个纹理(例如QPixamp )并在QBrush中使用它

参见QBrush(const QPixmap&)

对于纹理,您可以加载图像或使用QPainter创建图像

QPixmap pixmap(16, 16);
pixmap.fill(QColor(0, 0, 255));
QPainter painter(&pixmap);
painter.fillRect(pixmap.rect(), QBrush(QColor(128, 128, 128), Qt::DiagCrossPattern));