Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Text of QPushButton centered but left if text is to long
Forum Updated to NodeBB v4.3 + New Features

Text of QPushButton centered but left if text is to long

Scheduled Pinned Locked Moved General and Desktop
2 Posts 2 Posters 3.8k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    rubikon
    wrote on 23 May 2013, 06:12 last edited by
    #1

    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

    1 Reply Last reply
    0
    • R Offline
      R Offline
      raven-worx
      Moderators
      wrote on 23 May 2013, 06:35 last edited by
      #2

      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
      this->setText(text);

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

      }
      @

      --- SUPPORT REQUESTS VIA CHAT WILL BE IGNORED ---
      If you have a question please use the forum so others can benefit from the solution in the future

      1 Reply Last reply
      0

      1/2

      23 May 2013, 06:12

      • Login

      • Login or register to search.
      1 out of 2
      • First post
        1/2
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved