Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text (alone) of a QToolButton

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.

like image 407
Phil Avatar asked Aug 06 '13 08:08

Phil


1 Answers

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;
like image 161
Sylvain V Avatar answered Sep 21 '22 22:09

Sylvain V