Override a stylesheet



  • In my project I have set a default background and text color for QWidget, which all the other widgets inherit. I would prefer not to have to set this for every type of widget I am using.

    However, if you set a default style at the widget level, how do you override that style for an individual element? In the attached example, I have set the background gray and text light gray for QWidget and I want to show a label with red text, but not all labels.

    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
    {
        QWidget *centralWidget = new QWidget(this);
        QVBoxLayout *verticalLayout = new QVBoxLayout(centralWidget);
        QLabel *label = new QLabel(centralWidget);
        verticalLayout->addWidget(label);
    
        // does not change label text color when setStyleSheet for QWidget
        setStyleSheet("QWidget {background-color: rgb(95,95,95); color: rgb(229,229,229);}");
    
        label->setText("TEST COLOR");
        QPalette palette = label->palette();
        palette.setColor(QPalette::WindowText, Qt::red);
        label->setPalette(palette);
    }
    

    The text is red without the setStyleSheet statement.



  • I've got a solution by subclassing QLabel and overriding the paintEvent. Any comments on this are most welcome.

    DropShadowLabel::DropShadowLabel(QWidget *parent) : QLabel(parent)
    {
    
    }
    
    void DropShadowLabel::paintEvent(QPaintEvent *event)
    {
        QPainter painter(this);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
    
        QRect rect1(1,1,this->width()-2,this->height()-2);
        QRect rect2(3,3,this->width()-2,this->height()-2);
        painter.setPen(Qt::black);
        painter.drawText(rect2, text());
        painter.setPen(Qt::white);
        painter.drawText(rect1, text());
    }


  • @Rory_1 said:

    However, if you set a default style at the widget level, how do you override that style for an individual element?

    If you want to set a style sheet for one element, first, you have to give it a name:

    AnyQtWidget* myWidget = new AnyQtWidget;
    myWidget->setObjectName("MySpecialWidget");
    

    Then, you can set its style:

    setStyleSheet("AnyQtWidget#MySpecialWidget {"
      "stuff"
    "}");
    

    This way, the style sheet will apply on your special widget only.



  • Thanks very much. That is what I was looking for.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.