Search code examples
qtlayoutpyqtqt-designer

Qt button take as much space as the text on it needs


I have a button in Qt Designer and I want it to take always as much space as the text on it needs. How can i accomplish that?

I mean like the text on the button is "Hello" and the button will be 45px.

When I do self.button.setText("Hello World") the button will be 85px.

My current "servers.ui":

<item>
<widget class="QPushButton" name="pageLabel">
 <property name="sizePolicy">
  <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
   <horstretch>0</horstretch>
   <verstretch>0</verstretch>
  </sizepolicy>
 </property>
 <property name="maximumSize">
  <size>
   <width>40</width>
   <height>16777215</height>
  </size>
 </property>
 <property name="text">
  <string/>
 </property>
 <property name="flat">
  <bool>true</bool>
 </property>
</widget>
</item>

I'm actually talking about:

https://i.sstatic.net/z6tqe.png


Solution

  • Use a QToolButton instead of a QPushButton and clear its maximum size.

    You may need to set the vertical size-policy to "Preferred" so that it to has the same height as the other buttons. To get a flat button, check the "autoRaise" property.

    A quick way to change the button class is to right-click it and select "Morph Into" from the context menu.