QListWidget::setStyleSheet() 和 QListWidgetItem::setBackgroundColor() 关系

QListWidget::setStyleSheet() and QListWidgetItem::setBackgroundColor() relation

所以我有一个 QListWidget 对象,我设置为:

ui.myQListWidget->setStyleSheet("QListWidget::item { border-bottom: 1px solid black; }")

就在构建对象之前。

然后我想在我新创建的 QListWidget 列表中添加一些 QListWidgetItem 对象。

我有这样的东西:

if(stuff) {
    myqlistwidgetitem->setBackgroundColor(Qt::GlobalColor::darkGray);
}
else if(other_stuff) {
    myQListWidgetItem->setBackgroundColor(Qt::GlobalColor::lightGray);
}

ui.myQListWidget->addItem(myQListWidgetItem);

问题是所有元素都是白色的(而不是我指定的 darkGray 或 greenDark)。

仅当我省略 QListWidget::setStyleSheet() 调用时,元素才会以指定的颜色着色(但我没有项目之间的边框)。

我如何解决这个问题? (我需要彩色项目和它们之间的边框)。

如果这是你想要的结果

您可以子类化 QStyledItemDelegate,覆盖 paint() 方法并将其设置为您的 listWidget 的 itemDelegate。我不懂 C++,但我想,你可以从我的 python3/ pyqt5 示例中看到方法:

class myDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None):
        QtWidgets.QStyledItemDelegate.__init__(self)  
        self.setParent(parent)
        # offset item.rect - colored rect
        self.offset = 2 
        # different backgroundcolors
        self.brush = QtGui.QBrush(QtGui.QColor('white'))
        self.brush1 = QtGui.QBrush(QtGui.QColor('darkGray'))
        self.brush2 = QtGui.QBrush(QtGui.QColor('lightGray')) 
        # textcolor
        self.textpen = QtGui.QPen(QtGui.QColor(0,0,0))
        # linecolor and -width
        self.linePen = QtGui.QPen(QtGui.QColor(0,0,0))
        self.linePen.setWidth(2)
        # Alignment
        self.AlignmentFlag = QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter

    def paint(self, painter, option, index):
        # rect to fill with backgroundcolor
        itemRect = option.rect.adjusted(self.offset, self.offset, -self.offset, -self.offset)
        # text of the item to be painted
        text = self.parent().item(index.row()).text() 
        painter.save()
        # conditions for different backgroundcolors
        if text[0] == 'a':
            color = self.brush1
        elif text[0] == 'C':
            color = self.brush2
        else:
            color = self.brush
        # paint backgroundcolor
        painter.fillRect(itemRect,color)
        # paint text
        painter.setPen(self.textpen)
        painter.drawText(itemRect, self.AlignmentFlag, text)
        # paint bottom border
        painter.setPen(self.linePen)
        painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
        painter.restore()

另一种可能性是给您的项目一个 属性,然后在样式表中对 属性 作出反应。

例如,在您编写的代码中:

ui.myLabel->setProperty("stuff","1");
ui.myOtherLabel->setProperty("stuff","2");

然后在 qss 中你会写:

QLabel[stuff="1"] {
    background-color: #7777ff;
}
QLabel[stuff="2"] {
    background-color: #ff5555;
}

我没有 QListWidgetItem 的示例,但它应该可以类似地工作。