Search code examples
c++qtstylesheetqlistwidget

Style text of selected element in QComboBox or QListWidget?


Is it possible, using stylesheets, to change the appearence of the text contained in a selected item such as a QComboBox or a QListWidget? I've tried with a QListWidget but I can change everything except for the text properties.

This sample changes the text color but not its font:

QListWidget m_pListMain = new QListWidget(this);
m_pListMain->setStyleSheet("QListWidget:item:selected{"
                               "color: red;"
                               "font: bold;"
                               "}");

This, instead, works correctly:

QListWidget m_pListMain = new QListWidget(this);
m_pListMain->setStyleSheet("QListWidget{"
                               "color: red;"
                               "font: bold;"
                               "}");

But obviously it changes all the items, not just the selected one. What am I missing? (I am assuming the problem is the same with the QComboBox).


Solution

  • The only way I found is by connecting to this SIGNAL http://doc.qt.io/archives/qt-4.8/qlistwidget.html#currentItemChanged :

    currentItemChanged(QListWidgetItem*,QListWidgetItem*)
    

    then, in a SLOT, switch the font at runtime:

    _HandleListItemChanged(QListWidgetItem *p_pItemCurrent, QListWidgetItem *p_pItemPrevious)
    {
    // Switch fonts: only selected must be bold
        QFont l_Font = p_pItemCurrent->font();
        l_Font.setBold(true);
        p_pItemCurrent->setFont(l_Font);
    
        l_Font = p_pItemPrevious->font();
        l_Font.setBold(false);
        p_pItemPrevious->setFont(l_Font);
    }