[Python] How can I change the color for selected (highlighted) items in a QListWidget (Qt,...

Discussão em 'Python' iniciado por Stack, Setembro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a QListWidget subclass that will have just a cyan border when an item is selected

    But when I use transparent in its stylesheet I get a gray-like color (in fusion style) and when I go with normal style I get a whole white color

    I just want to have a cyan border with the existing background color

    Here's my code:

    import sys
    from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout,
    QListWidget, QListWidgetItem)
    from PySide6.QtCore import Qt
    from PySide6.QtGui import QFont
    from PySide6.QtWidgets import QApplication
    from PySide6.QtGui import QFont, QColor

    class NewListWidget(QListWidget):
    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.setStyleSheet("""
    QListWidget::item:selected {
    background-color: transparent;
    border: 2px solid #00AEEF;
    }
    """)
    # Other things

    class MainWindow(QMainWindow):
    def __init__(self):
    super().__init__()
    self.setWindowTitle('Study Planner')
    self.resize(210,210)

    central = QWidget()
    self.setCentralWidget(central)
    layout = QVBoxLayout(central)

    self.item_list = NewListWidget()
    self.item_list.setFixedHeight(200)
    sample_items = {
    'item1': ["#8f0000"],
    'item2':["#000073"],
    'item3':["#166300"],
    }

    for item_name,data in sample_items.items():
    a = QListWidgetItem(item_name)
    a.setTextAlignment(Qt.AlignCenter)
    a.setForeground(QColor("#FFFFFF"))
    a.setBackground(QColor(data[0]))
    self.item_list.addItem(a)

    self.item_list.setFont(QFont("Times new roman",14))
    self.item_list.setFixedWidth(200)

    layout.addWidget(self.item_list)
    if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('fusion')

    win = MainWindow()
    win.show()
    sys.exit(app.exec())



    This is what I get (fusion style):

    unselected : [​IMG]

    selected : [​IMG]

    Also in normal style:

    unselected: [​IMG]

    selected:[​IMG]

    Continue reading...

Compartilhe esta Página