Qt World Summit: Submit your Presentation

Text of QPushButton centered but left if text is to long

  • Hello.

    I want the texts of my QPushButton to be aligned centred. I know how to do that.

    The texts of the buttons can change at runtime and it could be that the text are to long to be displayed entirely on the button. If this happens, the beginning and the end of the text are not displayed. In that case I want the text to be left aligned so that only the end of the text is cut off.

    Is it possible to achieve this behaviour for QPushButton?

    Thank you in advance

  • Moderators

    You need to subclass the button and implement a custom method for setting the text.

    This should do what you want (assuming you have only buttons with text - without icons):

    void MyButton::setAlignedText(const QString & text)
    //set text

    //determine alignment
    QStyleOptionButton option;
    QRect textContentsRect = this->style()->subElementRect(QStyle::SE_PushButtonContents, &option, this);
    QFontMetrics fontMetrics(this->font());
    if( fontMetrics.width(text) <= textContentsRect.width() )
        //set centered aligned
        //set left aligned


Log in to reply