0

I have a TextCtrl with style=wx.TE_CENTRE, and I want/expect its contents to remain centered when I resize the TextCtrl. However, the text stays on the left side of the TextCtrl.

import wx

class MyApp(wx.App):
    def OnInit(self):
        frame = wx.Frame(None)
        frame.Show(True)
        self.SetTopWindow(frame)
        self.myText = wx.TextCtrl(frame, value="A", style=wx.TE_CENTRE)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.myText, wx.EXPAND)

        frame.SetSizer(sizer)
        sizer.Fit(frame)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        return True

    def OnSize(self, evt):
        self.myText.SetValue("after resize")

myApp = MyApp(0)
myApp.MainLoop()

After a lot of trial and error, I got it to work by doing both of the following:

  • Refresh the TextCtrl in my wx.EVT_SIZE handler
  • Add the style wx.TE_RICH to the TextCtrl

Why are both of these necessary? I'd like to understand what I'm doing wrong here. (I'm using wxPython 4.0.4 on Win7.)

1 Answers1

0

It may be your environment, it certainly works normally on Linux using wx 4.0.4
It could be down to the fact that you are doing it all within a wx.App class.
Conventionally this code would be written something like this:

import wx

class MyFrame(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self,parent,-1,("My Frame"), size=(200,100))
        self.myText = wx.TextCtrl(self, value="A", style=wx.TE_CENTRE)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.myText, wx.EXPAND)
        self.SetSizer(sizer)
        self.Show()

myApp = wx.App()
frame = MyFrame(None)
myApp.MainLoop()

Does this code misbehave in the same way?

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
  • Your code **does** work on Win7. However, if I add a wx.EVT_SIZE handler, it breaks. That is, **unless** I add evt.Skip() to the handler. Subsequently, I've discovered that my original code *does* work, if I add evt.Skip() to my wx.EVT_SIZE handler(!). Thanks for your answer; it nudged me in the right direction. – TheFrankster Apr 29 '19 at 15:55