1

I have a custom QWidget class that does not seem to be inheriting its parent's stylesheet as I understand it should. I print out the parent stylesheet in my custom class's constructor and it's definitely the correct parent with the correct stylesheet.

MyWidget::MyWidget(QWidget *parent_) :
    QWidget(parent_)
{
    std::cout << "parent is " << parent_->objectName().toStdString() << std::endl;
    std::cout << "stylesheet is: " << parent_->styleSheet().toStdString() << std::endl;

However, I found I can get it to work If I call this in the constructor:

   setStyleSheet(parent_->styleSheet());

My understanding is that this should not be necessary. It doesn't seem to be required for other widgets in my program. What could I be doing wrong that would prevent this from working?

KyleL
  • 1,379
  • 2
  • 13
  • 35

2 Answers2

2

It turns out MyWidget is reparented at some point and that new parent had a rogue stylesheet that was overriding the master cascaded stylesheet. Removing that intermediate stylesheet caused everything to start working again.

KyleL
  • 1,379
  • 2
  • 13
  • 35
1

You can do this with one single styleSheet.

Give to your widget subclass objectName:

widget->setObjectName("family");
widget_2->setObjectName("family");

Apply stylesheet:

qApp->setStyleSheet(stylesheet);

where stylesheet has next code:

#family
{
background-color: green
}

All widgets with family object name get this stylesheet.

If you set:

widget->setObjectName("family");//only this widget has stylesheet
widget_2->setObjectName("notFamily");

Why is it good? You can wrote special styleSheet with settings to all elements, save it as file, put it into resource and use it, it is easy to debug, because your stylesheets placed in one place,

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • This is basically what I'm trying to do with my parent's style sheet. There are common settings that should apply to both the parent and child QWidgets. I'm just not sure why its not automatically cascading. The cascade seems to work fine in other instances, so I don't know what it is about the MyWidget class above that doesn't work with the cascade. – KyleL Sep 17 '14 at 16:20
  • @KyleL you want to say that when you write QWidget{background-color: green} your MyWidget doesn't change? – Jablonski Sep 17 '14 at 16:25