简体   繁体   English

自定义QWidget不继承父样式表

[英]Custom QWidget is not inheriting parent stylesheet

I have a custom QWidget class that does not seem to be inheriting its parent's stylesheet as I understand it should. 我有一个自定义QWidget类,据我了解,它似乎并没有继承其父级的样式表。 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? 我可能做错了什么而使它无法正常工作?

You can do this with one single styleSheet . 您可以使用一个styleSheet做到这一点。

Give to your widget subclass objectName : 给您的小部件子类objectName

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

Apply stylesheet : 应用stylesheet

qApp->setStyleSheet(stylesheet);

where stylesheet has next code: stylesheet具有下一个代码:

#family
{
background-color: green
}

All widgets with family object name get this stylesheet . 所有具有族对象名称的小部件都将获得此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, 您可以编写具有所有元素设置的特殊styleSheet,将其保存为文件,将其放入资源中并使用它,这很容易调试,因为您的样式表放在一个位置,

It turns out MyWidget is reparented at some point and that new parent had a rogue stylesheet that was overriding the master cascaded stylesheet. 事实证明,MyWidget在某个时候已重新创建父级,并且新父级的流氓样式表已覆盖了主级联样式表。 Removing that intermediate stylesheet caused everything to start working again. 删除该中间样式表会使所有内容重新开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM