⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

QLabel How to change background color and have a border without stylesheet?

  • Hi,

    So i want to have a QLabel with a certain background color aswell as a black border. Using stylsheets this is done in one line, however i was wondering if it is possible without it and how this would be done.

                QLabel* l = new QLabel();
                QPalette palette;
                palette.setColor(QPalette::Window, Qt::red);
                l->setFixedSize(200, 100);

    This is how one can change the background color. How would i now add a black border?

  • Lifetime Qt Champion

    Well you could put it inside a QFrame and have it that way
    or simply make a QLabel subclass that does as you want.

    #include <QLabel>
    class BorderLabel : public QLabel
        explicit BorderLabel(QWidget *parent = Q_NULLPTR) : QLabel(parent)
        virtual void paintEvent(QPaintEvent *event) override
            QPainter p(this);
            p.setPen(QPen(Qt::black, 2));
            p.drawRect(0, 0, width(), height());
            QLabel::paintEvent(event); // draw normally

    alt text

  • @Infestor Do this below your code

    QFrame *f=qobject_cast<QFrame *>(l);

  • Thank you this worked.

  • I would really suggest to go with a stylesheet. I don't see a reason why not (never had any issues that it would be too slow or anything).

    Changing the palette might work for some widget types on some platforms. If you use the native style on Windows or Mac OS you will eventually run into problems that you cannot change any part of the palette to influence some of the colors. You could try to use proxy styles to change colors of certain widgets. But, this is very messy compared to just plain stylesheets. Qt used to have setBackgroundColor() at one point, but it slowly faded out. So, as long as you don't have any specific good reason to not use stylesheets, go with stylesheets as they will make your life a lot easier. (I personally wish as well that we did not have to use stylesheets. After fighting it for quite a while I finally gave in because there is no better way in Qt.)

Log in to reply