Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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->setPalette(palette);
                l->setAutoFillBackground(true);
                l->setFixedSize(200, 100);
                l->setText("text");
    

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


  • Lifetime Qt Champion

    Hi
    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
    {
        Q_OBJECT
    
    public:
        explicit BorderLabel(QWidget *parent = Q_NULLPTR) : QLabel(parent)
        {
        }
    protected:
        virtual void paintEvent(QPaintEvent *event) override
        {
            QPainter p(this);
            p.setPen(QPen(Qt::black, 2));
            p.setBrush(Qt::red);
            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);
    f->setFrameShape(QFrame::Shape::Box);
    f->setLineWidth(1);


  • 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