pythonwxpythonsizer

wxpython: Center and right align two controls horizontally at the same time


I have two controls in a horizontal sizer. How can I get one of them to be aligned left(or right) and the other to be centered?

import wx
from wx.lib.stattext import GenStaticText

class PageNavigator(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour((179, 179, 179))

        self.scrollbar = wx.Slider()
        self.scrollbar.Create(self)

        self.pagenum_txtctrl = GenStaticText(self, label="Page 1")

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.pagenum_txtctrl, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, 0)
        #sizer.AddStretchSpacer(1)
        sizer.Add(self.scrollbar, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, 0)
        #sizer.AddStretchSpacer(1)
        self.SetSizer(sizer)

I would be great if I could specify how to set the width of the text control to be zero. This could trick the sizer into centering the slider properly. However, it's still not an elegant method.


Solution

  • You cannot have two items in a simple BoxSizer and have each item aligned differently. That is not supported. Instead, I would just add a wx.Spacer object in (or perhaps a couple of them) and have them expand to help you control your layout.

    Or you could just use a GridSizer with three columns and put the middle widget in the middle column.