Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styling text regions with class selector from global QSS

How can I style a span that is part of a widget text (e.g. a QLabel) via global style sheet?

E.g. in below example, both foo and bar should be red.

#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>

class
some_label : public QLabel
{
    Q_OBJECT
public:
    some_label(QString text = "") : QLabel(NULL) {
        setText(text);
        show();
    };
};
#include "main.moc"

static const char *css =
        "some_label { color : blue; background : black; }"
        "span.some_class { color : red; }";

int
main(int argc, char **argv)
{
    QApplication a(argc, argv);
    a.setStyleSheet(css);
    some_label label("before "
                     "<span style=\"color:red;\">foo</span> " /* works */
                     "<span class=\"some_class\">bar</span> " /* fails */
                     "after");
    return a.exec();
}

Qmake (Qt 5.1.1) project file:

QT      += widgets
SOURCES += main.cpp

Unsatisfactory result

I would really appreciate a solution that avoids hardcoding the style as I did with the foo span. The goal is for the application look to be determined entirely by a user-supplied style sheet (represented by css in the example). At the moment I use a workaround involving separate labels for each element that is colored and it is a nightmare to maintain.

I have consulted a few online sources as well as Blanchette/Summerfield chapter 19 but those are primarily concerned with styling whole widgets.

like image 644
Philipp Gesang Avatar asked Nov 04 '13 17:11

Philipp Gesang


1 Answers

If you don't need to change styling after the QLabel loads, you could devise a system where you text-replace the colors you want for each word from a centralized style file:

// These values come from a central, user-supplied style sheet, etc.
QString primary = "red";
QString secondary = "green";

some_label label("before "
                 "<font color=\"" + secondary + "\">foo</font> "
                 "<font color=\"" + primary   + "\">bar</font> "
                 "after");

This system is a little hard to read but it could be an improvement over using many QLabels.

(As you may have noticed, Qt doesn't support CSS selection of classes within QLabels.)

like image 59
scarcegreengrass Avatar answered Nov 05 '22 15:11

scarcegreengrass