1、下沉原因
1.1、QPushButton源码
void QPushButton::initStyleOption(QStyleOptionButton *option) const { if (d->down || d->menuOpen) option->state |= QStyle::State_Sunken; if (d->checked) option->state |= QStyle::State_On; }
当按下和选中后
option->state 会有 QStyle::State_Sunken 或者 QStyle::State_On 标记
1.2、QCommonStyle 源码
void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *widget) const { Q_D(const QCommonStyle); switch (element) { case CE_PushButtonLabel: if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) { if (button->state & (State_On | State_Sunken)) textRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget), proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget)); proxy()->drawItemText(p, textRect, tf, button->palette, (button->state & State_Enabled), button->text, QPalette::ButtonText); } break; } }
当 option->state 含有 QStyle::State_Sunken 或者 QStyle::State_On 标记时 会改变文本位置
2、解决办法
2.1、设置样式代理
proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget) proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget)
获取偏移时return 0;
时间: 2024-10-23 13:35:06