Python Forum

Full Version: How to get the color name of qlistwidget?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm trying to get the color name of the current item's foreground of a qlistwidget.

To set it I used:
self.listbox_medium.insertItem(0, "paper")
self.listbox_medium.item(0).setForeground(QColor("blue"))
To get the color name I tried:

    def button_apply_selection_clicked(self):
        if self.listbox_medium.currentItem().foreground().color().colorNames() == QColor("blue"):
            print("okay")
        else:
            print("bad")
In the listbox (qlistwidget) I've got 2 items:
one with a blue foreground,
one with a green foreground.

But if I try to check for "blue" or "green", it is always returned "bad"...

I couldn't find the correct syntax for checking for the color names...

Could you please give me a hint?

Thanks a lot...
You could comapare color objects.
Output:
if self.listbox_medium.currentItem().foreground().color() == QColor("blue"):
colornames() is not going to be useful. It returns a list of all colornames that Qt knows about. The list has nothing to do with any particular color.
Maybe it's easier with hex

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QListWidgetItem
from PyQt5.QtGui import QColor


class Ui_MainWindow(QWidget):
    def __init__(self, parent = None):
        super(Ui_MainWindow, self).__init__(parent)
        self.window = QWidget()
        self.listWidget = QListWidget()
        self.window.setWindowTitle("ListWidget")
        
        self.listWidget.currentItemChanged.connect(self.index_changed)

        listWidgetItem = QListWidgetItem("Hello World")
        listWidgetItem.setForeground(QColor("#0000ff")) # blue
        self.listWidget.addItem(listWidgetItem)
        
        listWidgetItem = QListWidgetItem("Hello World")
        listWidgetItem.setForeground(QColor("#ff0000"))
        self.listWidget.addItem(listWidgetItem)
        
        self.listWidget.setCurrentRow(1)

        window_layout = QVBoxLayout(self.window)
        window_layout.addWidget(self.listWidget)
        self.window.setLayout(window_layout)
        self.window.show()
            
    def index_changed(self, item):
        if item.foreground().color().name() == "#0000ff": # blue
            print("is blue")
        else:
            print("is not blue")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Ui_MainWindow()
    sys.exit(app.exec_())
Doesn't matter if you use the color name, or RGB.
from PySide6.QtGui import QColor
print(QColor("blue") == QColor("blue"))
print(QColor("blue") == QColor("red"))
print(QColor("blue") == QColor("#0000ff"))
Output:
True False True
Either way in is a bad idea using color as a state.
Yes, but item.foreground().color().name() returns hex color.
Dear deanhystad,
dear Axel_Erfurt!!

Thanks a lot for your answers, it helped me much...