参考官方文档subclass from QWidget
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
The above code is a no-operation if there is no stylesheet set.
对于一个子组件,其styleSheet可以在以下几个地方设置:
子组件ui中设置
、子组件源码中设置
、父组件ui中设置
、父组件源码中设置
这几个地方setStyleSheet,执行时的顺序是怎样的?
在xxx.cpp和ui_xxx.cpp文件中找到对应的setStyleSheet下断点可知执行顺序为:
子组件ui中设置
->子组件源码中设置
->父组件ui中设置
->父组件源码中设置
尽量规范约定好setStyleSheet位置,如自定义子组件仅在子组件中setStyleSheet,父组件不重复设置,防止setStyleSheet覆盖
例如以下的styleSheet:
QPushButton[stateColor=‘red‘]
{
background-color: rgb(170, 0, 0);
}
QPushButton[stateColor=‘green‘]
{
background-color: rgb(0, 170, 0);
}
使用时,想要切成绿色,
ui->pushButton->setProperty("stateColor","green");
ui->pushButton->style()->unpolish(ui->pushButton);
ui->pushButton->style()->polish(ui->pushButton);
原文:https://www.cnblogs.com/SwiftChocolate/p/15310960.html