MEL How-To #21

Back · Previous · Next Maya

How do you center a button (or any other UI control) in a layout?

To do this is not difficult, but arguably it is a bit more work than it could be.

A UI control must be attached to something else; it will float freely in the UI if its attachment is "None". There is no "center" alignment as is common with the contents of a control.

In the columnLayout or rowLayout, attachments are defined using the ‘−columnAttach’ and ‘−rowAttach’ attributes. But honestly, I never use those, and they wouldn't give you any centering abilities, anyway.

Your best bet for getting what you want is to use a formLayout. Granted, there is no magic "center button" feature for this, either, but you can achieve the same thing using the attachment commands:

  string $form = `formLayout`;
    string $button = `button -label "Centered Button"`;
    setParent ..;

  formLayout -e
    -attachPosition  $button    left    0  25
    -attachPosition  $button    right   0  75


Here I've attached the left and right sides of the button an equal distance from each side of the form. A formLayout has, by default, 100 divisions. This layout leaves 25 units of space on each side, effectively centering the button.

Please refer to: