Please nominate your Qt Champions for 2021!

Editing qss stylesheet programmatically

  • Hi everyone.

    I'm looking into a solution or idea how to edit an exiting .qss file. I have 4-5 qss files which I want to edit the file in Gui without doing manually.

    fx. I have bunch of items and I want to edit the QLabel's color.

    color: #aaaaaa;

    How am I going to archieve this?

  • Moderators


    1. get the qss from the widget using QWidget::stylesheet()
    2. set the returned qss to a QTextEdit and edit it
    3. when finished set the qss QTextEdit::toPlainText() back to the same widget where you got it from using QWidget::setStyleSheet()

  • Yea but the issue here is that the "user" have to edit the qss manually. What I want to archieve is in my GUI I have few QLineEdit with qColorDialog (For QLabel, textsize and background) . So user needs only to pick a color and "somehow" replace the chosen color.
    fx. if I Choose red in color picker, It have to update the qss with the value I have picked.

  • Moderators


    QColor color = QColorDialog::getColor(...);
    widget->setStyleSheet( QString(
    "QLabel {"
    "color: %1;"
    ).arg( ) );

    If the qss can be predicted, than there is no way around parsing the qss and replace the value.

  • @raven-worx

    I see. But what would the default value of color be before setting the color? can I do sth like this

    "color: %1#fffffff;"

  • Moderators

    the default color is decided by the platform style.
    So you should ask the widget's QPalette:

    widget->palette().color( QPalette::Text );

    Which color group excactly depends on the widget type. But i think mostly it should be QPalette::Text for the text.

    In my example the %1will be replaced with the value passed to arg()
    So you need to remove it, when you are not calling the arg() method on the string.

  • Okay thanks a lot!

    I will try to see if I can get it to work :)

Log in to reply