Qt6 topics merged with General

How to change the Text Color of a List Item ?

  • Hello

    I am trying to change the color of a text in a ListView.
    I can change the text color of a Qlabel, for instance, not for a item in a list...

    Currenltly, my code is the following:

    QListWidgetItem* w = ui->w_MessageList->item(2);
    w->setBackgroundColor(QColorConstants::Svg::plum);   // This change background color. It is deprecated but it works.
    // Attempt to change the foreground (text) color
    QBrush b = w->foreground().style();       // get the brush of the text
    b.setColor(QColorConstants::Svg::pink);   // change the brush
    w->setForeground(b);                      // apply the brush

    But the text is still black.
    Can you help on how to use the Qbrush (or the Qstyle) ?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    What version of Qt ?
    What OS ?
    Can you provide a minimal compilable example that shows that behavior ?

  • Hello @SGaist ,
    Here is the minimal compilable code (Qt 5.15 under Windows):
    With this program, I create a list and add 3 items.
    Then, I try to change the ForegroundColor of an item, to make the text appear Red, but all the texts of the 3 items remain black.
    I don't undertand why.
    Thanks for your help.

    #include <QApplication>
    #include <QListWidget>
    int main(int argc, char *argv[])
        QApplication a(argc, argv);
        QWidget fenetre;
        fenetre.setFixedSize(320, 320);
        QListWidget w_MessageList(&fenetre);
        w_MessageList.addItem("first list item");
        w_MessageList.addItem("second list item");
        w_MessageList.addItem("third list item");
        // Attempt to change the color of the text of the second item.
        QListWidgetItem* w = w_MessageList.item(1);
        QBrush b = w->foreground().style();      // get the brush
        b.setColor(QColorConstants::Red);        // change the brush
        w->setForeground(b);                     // apply the brush
        // w->setBackgroundColor(QColorConstants::Yellow);  // this change the background color (deprecated by Qt)
        return a.exec();

  • @Sphinkie Hello
    I'm not sure what is your QColorConstants::Red.
    But I've tested your code withQt::red and it works, the second item's text is red.

    And setBackgroundColor is deprecated because since 4.2 we should use setBackground.
    Also, you could directly pass a QColor object as a QBrush parameter.


  • @Bonnie said :


    Thank you. This works very well.

    (and also:


    Colors are from https://doc.qt.io/qt-5/qcolorconstants.html

  • @Sphinkie
    Wow, I had not noticed there is such a namespace since I'm still mainly using 5.12.
    If the constants are QColor objects as the doc says, then you should be able to use them directly like