无法在 qt 中为来自 QWidget 的派生 class 设置样式 sheet
Can't set style sheet for a derived class from QWidget in qt
我从 QWidget
派生了一个 class,我们称它为 DerivedWidget
。我将 MainWindow
class 中的 DerivedWidget
设置为中央小部件。我想更改 DerivedWidget
的背景颜色,我尝试了很多方法,但都行不通。
DerivedWidget::DerivedWidget(QWidget *parent) : QWidget(parent)
{
mBtn = new QPushButton(this); //if I have some other widgets on this, like a QPushButton
mBtn->setStyleSheet("QPushButton { background-color: red; }"); //it works for the QPushButton on this widget
//tried three ways below to set the widget bgcolor, none of them works
//first
this->setStyleSheet("QWidget { background-color: yellow; }"); //it is not working
//second
this->setObjectName("#DerivedWidget");
this->setStyleSheet("QWidget#DerivedWidget { background-color: yellow; }"); //still not working
//third
this->setStyleSheet("DerivedWidget { background-color: yellow; }"); //not working either
}
如您所见,我可以更改 DerivedWidget
上的小部件的样式 sheet,但不能更改其背景颜色。
我还尝试更改 MainWindow
class 中的 DerivedWidget
bgcolor。当然,我尝试了比我提供的三种方法更多的方法,但结果还是一样。 None 这些方法奏效了。如果我只是创建一个 QWidget
并将其设置为 MainWindow
class 中的中央小部件,我可以轻松地为此设置 bgcolor。但是为什么我不能为派生的 class?
设置 bgcolor
为什么会发生这种情况,我该如何解决这个问题?
好的,我通过重新实现 paintEvent(QPaintEvent *)
函数解决了这个问题,例如:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
这里有更多详细信息:Qt Doc and a helpful answer。
我从 QWidget
派生了一个 class,我们称它为 DerivedWidget
。我将 MainWindow
class 中的 DerivedWidget
设置为中央小部件。我想更改 DerivedWidget
的背景颜色,我尝试了很多方法,但都行不通。
DerivedWidget::DerivedWidget(QWidget *parent) : QWidget(parent)
{
mBtn = new QPushButton(this); //if I have some other widgets on this, like a QPushButton
mBtn->setStyleSheet("QPushButton { background-color: red; }"); //it works for the QPushButton on this widget
//tried three ways below to set the widget bgcolor, none of them works
//first
this->setStyleSheet("QWidget { background-color: yellow; }"); //it is not working
//second
this->setObjectName("#DerivedWidget");
this->setStyleSheet("QWidget#DerivedWidget { background-color: yellow; }"); //still not working
//third
this->setStyleSheet("DerivedWidget { background-color: yellow; }"); //not working either
}
如您所见,我可以更改 DerivedWidget
上的小部件的样式 sheet,但不能更改其背景颜色。
我还尝试更改 MainWindow
class 中的 DerivedWidget
bgcolor。当然,我尝试了比我提供的三种方法更多的方法,但结果还是一样。 None 这些方法奏效了。如果我只是创建一个 QWidget
并将其设置为 MainWindow
class 中的中央小部件,我可以轻松地为此设置 bgcolor。但是为什么我不能为派生的 class?
设置 bgcolor
为什么会发生这种情况,我该如何解决这个问题?
好的,我通过重新实现 paintEvent(QPaintEvent *)
函数解决了这个问题,例如:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
这里有更多详细信息:Qt Doc and a helpful answer。