2024-09-30 18:31:15 发布
网友
我有一个QToolButton。我用它来代替QPushButton,因为我需要一个类似lookingbutton的标签。即使将样式表的边框和填充设置为None-0px,QPushButton也太粗。在
None-0px
我希望这个QToolButton包含一个文本(没有图标)右对齐。在
但是,text-align: right;不起作用。.setAlignment(Qt.AlignRight)也不工作。在
text-align: right;
.setAlignment(Qt.AlignRight)
如何将文本向右对齐?在
谢谢。在
此示例将按钮内容(图标和文本)居中对齐,但您可以根据需要采用此示例(向右对齐)。下一步重写QToolButoon::paintEvent:
void CMyToolButton::paintEvent( QPaintEvent* ) { QStylePainter sp( this ); QStyleOptionToolButton opt; initStyleOption( &opt ); const QString strText = opt.text; const QIcon icn = opt.icon; //draw background opt.text.clear(); opt.icon = QIcon(); sp.drawComplexControl( QStyle::CC_ToolButton, opt ); //draw content const int nSizeHintWidth = minimumSizeHint().width(); const int nDiff = qMax( 0, ( opt.rect.width() - nSizeHintWidth ) / 2 ); opt.text = strText; opt.icon = icn; opt.rect.setWidth( nSizeHintWidth );//reduce paint area to minimum opt.rect.translate( nDiff, 0 );//offset paint area to center sp.drawComplexControl( QStyle::CC_ToolButton, opt ); }
您可以尝试子类QStyle并重新实现QStyle::drawControl()以将文本向右对齐。检查文件qt/src/gui/styles/qcommonstyle.cpp看看是怎么做的。(对不起,我使用C++而不是Python)
case CE_ToolButtonLabel: if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) { QRect rect = toolbutton->rect; int shiftX = 0; int shiftY = 0; if (toolbutton->state & (State_Sunken | State_On)) { shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, toolbutton, widget); shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, toolbutton, widget); } // Arrow type always overrules and is always shown bool hasArrow = toolbutton->features & QStyleOptionToolButton::Arrow; if (((!hasArrow && toolbutton->icon.isNull()) && !toolbutton->text.isEmpty()) || toolbutton->toolButtonStyle == Qt::ToolButtonTextOnly) { int alignment = Qt::AlignCenter | Qt::TextShowMnemonic;
此示例将按钮内容(图标和文本)居中对齐,但您可以根据需要采用此示例(向右对齐)。下一步重写QToolButoon::paintEvent:
您可以尝试子类QStyle并重新实现QStyle::drawControl()以将文本向右对齐。检查文件qt/src/gui/styles/qcommonstyle.cpp看看是怎么做的。(对不起,我使用C++而不是Python)
相关问题 更多 >
编程相关推荐