Individual background color of the QListWidget when selected

I have a list of elements with a separate color in a QListWidget as part of a Python3 / PySide application. When choosing, I would like the elements to be highly elastic, using some color, while maintaining their respective background, i.e.

desired display

not the full color version shown in the following image

current display

Elements that are mainly highlighted using colors (background or not) can be rearranged using drag and drop. It is important that the user can always see what the current selection is.

Use selection-color: solid rgba(255, 0, 0, 50%);does not show the desired effect.

, SO: Selected QListWidgetItem QListWidget . ? ( PySide.QtGui.QListWidgetItem.setBackground(brush))? , , .

:

import sys
import collections
from PySide import QtCore, QtGui

class MainWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #definition of colors and brushes (for colored backgrounds)
        layers = collections.OrderedDict(
            {1:('greenItem','g'),
             2:('yellowItem','y'),
             3:('mixedItem','m')})
        brushes = {'y': QtGui.QColor(255,200,0),
                   'g': QtGui.QColor(0,  160,0)}
        texSIG = QtGui.QPixmap(200,1)
        texSIG.fill(brushes['g'])
        paint = QtGui.QPainter()
        paint.begin(texSIG)
        paint.fillRect(80, 0, 40, 1, brushes['y'])
        paint.end()
        brushes['m'] = texSIG
        #create list
        self.lst = QtGui.QListWidget(self)
        self.lst.setStyleSheet( """
                                QListWidget:item:selected:active {
                                     background-color:red;
                                }
                                """
                                )
        #comment on styling:
        #background-color on selection is plain red
        #something like "selection-color: solid rgba(255, 0, 0, 50%);" shows no effect

        self.lst.setSortingEnabled(False)
        for idx, d in layers.items():
            newItem = QtGui.QListWidgetItem('{:s}'.format(d[0]))
            newItem.setBackground(QtGui.QBrush( brushes[d[1]] ))
            newItem.setTextAlignment(QtCore.Qt.AlignVCenter)
            self.lst.addItem(newItem)
        self.lst.setSelectionMode(QtGui.QAbstractItemView.SelectionMode(QtGui.QAbstractItemView.ExtendedSelection))
        self.lst.setDragDropMode(self.lst.InternalMove)
        #setup and show window
        self.setMinimumWidth(200)
        self.setMinimumHeight(200)
        self.show()
#create gui
app = QtGui.QApplication(sys.argv)
#create and display main window
main = MainWindow()
main.show()
#return exit code
sys.exit(app.exec_())
+3

All Articles