//sheetstyle file, style.css
QWidget#setting_widget
{
background-color: white;
}
//child widget
class CSubWidget : public QWidget
{
Q_OBJECT
public:
explicit CSettingWidget(QWidget *parent = 0);
};
CSettingWidget::CSettingWidget(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(Qt::WindowStaysOnTopHint);
setObjectName("subwidget");
}
//main widget
class MainWindow : public QWidget
{
Q_OBJECT
public:
~MainWindow();
explicit MainWindow(QWidget *parent = 0);
private:
CSubWidget *m_pSubWidget;
};
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)
{
QFile file(":/style.css");
file.open(QIODevice::ReadOnly);
qApp->setStyleSheet(file.readAll());
m_pSubWidget = new CSubWidget(this);
}
以上会发现, CSubWidget 设置的窗体样式是无效的,
查看文档会发现
QWidget
Supports only the background, background-clip and background-origin properties.
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.
Warning: Make sure you define the Q_OBJECT macro for your custom widget.