QStyleSheetStyle 调用 QCss::Parser 解析qss样式,
那什么时候这些样式起作用呢?
每个QWidget子类对象绘制都会调用其 paintEvent(),而在 paintEvent中会调用这些样式进行绘制,如:QPushButton中
void QPushButton::paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionButton option; initStyleOption(&option); p.drawControl(QStyle::CE_PushButton, option); }
QStyleOptionButton 会从QPushButton对象中获取相应的信息来初始化自己。drawControl内部会调用一系列接口根据样式绘制自己。
每个QWidget调用setStyleSheet方法设置样式,都会新建一个QStyleSheetStyle,其继承QWindowsStyle类,绘制由QStyle及其子类完成,而QStyleSheetStyle重载基类的绘制控件的方法
class QStyleSheetStyle : public QWindowsStyle { typedef QWindowsStyle ParentStyle; Q_OBJECT public: QStyleSheetStyle(QStyle *baseStyle); ~QStyleSheetStyle(); void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *w = 0) const Q_DECL_OVERRIDE; void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w = 0) const Q_DECL_OVERRIDE; void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const Q_DECL_OVERRIDE; void drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal, bool enabled, const QString& text, QPalette::ColorRole textRole = QPalette::NoRole) const Q_DECL_OVERRIDE; void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p, const QWidget *w = 0) const Q_DECL_OVERRIDE; ... } void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p, const QWidget *w) const { RECURSION_GUARD(baseStyle()->drawControl(ce, opt, p, w); return) QRenderRule rule = renderRule(w, opt); int pe1 = PseudoElement_None, pe2 = PseudoElement_None; bool fallback = false; switch (ce) { case CE_ToolButtonLabel: if (const QStyleOptionToolButton *btn = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) { if (rule.hasBox() || btn->features & QStyleOptionToolButton::Arrow) { QCommonStyle::drawControl(ce, opt, p, w); } else { QStyleOptionToolButton butOpt(*btn); rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button); baseStyle()->drawControl(ce, &butOpt, p, w); } return; } break; ... }
从上面代码,可以看出qss是通过以上方式起效的。
附:QStyle子类间的关系