How to align text (separately) QToolButton

I have a QToolButton . I use it instead of QPushButton because I need a button that looks like a shortcut. QPushButton is too short even after setting the borders of the style sheets and scrolling to None-0px .

I would like this QToolButton to contain text (without an icon) aligning to the right.

However, text-align: right; does not work. .setAlignment(Qt.AlignRight) also does not work.

How to align text to the right?

Thanks.

+4
source share
2 answers

You can try subclassing QStyle and reimplementing QStyle :: drawControl () to align the text to the right. Check the qt / src / gui / styles / qcommonstyle.cpp file to find out how. (Sorry, I'm using C ++, not 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; 
+3
source

This example of the contents of the alignment button (icon and text) is centered, but you can apply this example to your requirements (right-justify). Override QToolButoon :: paintEvent as follows:

 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 ); } 
0
source

Source: https://habr.com/ru/post/1495477/


All Articles