How to center text on multi-line buttons?

Greetings,

Title pretty much says it all; if I make a button in Glade with a text label that has line-break(s) in it, the text on the label ends up being left aligned - and I would like it to be centered.

Longer version:

There is a set_justify() method on <label>s, which would accept "center" as a value - but the button label is a <property> of the <button>, not a fully fledged child widget. Still, looking at the result with the GTKInspector, I can see that a normal label widget gets created inside the button - though I have found no way to attach a class or ID to such an implicit label, or to access it programmatically. For example, builder.get_object("button1").get_property("label") returns a string, and not the actual label object, so there’s nothing for me to call the set_justify() method on. Furthermore, while I can call set_alignment() on the button itself, this only changes the alignment of the label bounding box as a whole, not the lines of text within it. I have spent hours looking for a solution and have come up short - so I have to ask for help!

Edit: As far as I have been able to determine, there is no way to achieve this with CSS alone.

You might actually want to add the label yourself to the button using button.add(label) where the label has all the properties and look you wish.

Yeah. I’d like to avoid doing that if at all possible; easier to keep track of the layout if it’s all in the XML. Could I perhaps manually add the label in the XML somehow? I mean, so that it’s a fully fledged label rather than just a <property> of the <button>?

GtkButton is a container widget, so you can add a child:

<object class="GtkButton" id="button1">
  <child>
    <object class="GtkLabel" id="button1_label">
      <property name="justify">center</property>
      <property name="label">Some text\nwith newlines\nembedded into it</property>
      <property name="visible">1</property>
    </object>
  </child>
</object>
1 Like

Perfect, that’s exactly what I was after. Probably obvious to anyone with experience, but I only started tinkering with GTK GUIs and Glade yesterday. I did find that \n rendered literally though; I had to use &#xD; to get the line break to appear.

Sure you can do it. Try out a demo in Glade to see how it works.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.