So I have a QListWidget
object, and I set this:
ui.myQListWidget->setStyleSheet("QListWidget::item { border-bottom: 1px solid black; }")
Right before the object is constructed.
Then I want to add some QListWidgetItem
objects in my new created QListWidget
list.
I have something like this:
if(stuff) {
myqlistwidgetitem->setBackgroundColor(Qt::GlobalColor::darkGray);
}
else if(other_stuff) {
myQListWidgetItem->setBackgroundColor(Qt::GlobalColor::lightGray);
}
ui.myQListWidget->addItem(myQListWidgetItem);
The problem is that all the elements will be white (and not darkGray or greenDark as I specified).
The elements will be colored in the specified colors only if I omit the QListWidget::setStyleSheet()
call (but then I don't have the border between items).
How I solve this? (I need colored items and border between them).
if this is the result you want
you can subclass QStyledItemDelegate
, overwrite the paint()
method and set it as itemDelegate to your listWidget. I don't know c++, but i think, you can see the way from my python3/ pyqt5 example:
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()