Reputation: 14671
I have a QToolButton. I'm using it instead of QPushButton because I need a label-like looking button. QPushButton is too chunky even after setting stylesheet's borders and paddings to None-0px
.
I would like this QToolButton to contain a text (no-icon) align right.
However, text-align: right;
is not working. .setAlignment(Qt.AlignRight)
is also not working.
How can I align the text to right?
Thank you.
Upvotes: 6
Views: 4801
Reputation: 253
This example of align button content (icon & text) to center, but you can adopt this example to your demands (align to right). Override QToolButoon::paintEvent as next:
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 );
}
Upvotes: 1
Reputation: 194
You can try to sub-class QStyle and re-implement QStyle::drawControl() to align the text to the right. Check the file qt/src/gui/styles/qcommonstyle.cpp to see how it's done. (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;
Upvotes: 4