pyNewbie
pyNewbie

Reputation: 155

wxpython textctrl autosize to fit text

Very simple question:

Ive got a wxpython textctrl box to which i want to display a long text. The text may contain newlines. may not.

No matter what i do, the box always seems to be a little short.

ive gone to the extent of getting the font size and trying to calculate the height needed, and the math seems to work, but the box is too short...width is fine and what i expect

sample of code here:

Message = 'really long text....just an example here............................................................................................................................'

self.MessageBoxText = wx.TextCtrl( self, wx.ID_ANY, Message, wx.DefaultPosition, wx.DefaultSize, wx.TE_RICH|wx.TE_MULTILINE|wx.TE_BESTWRAP)
self.MessageText.SetFont( wx.Font( 18, 74, 90, 90, False, 'Arial') )

dc = wx.WindowDC(self.panel)

textWidthSingle, textHeightSingle = dc.GetTextExtent(self.MessageBoxText.GetValue())

textWidth, textHeight,other =  
dc.GetMultiLineTextExtent(self.MessageText.GetValue(),self.MessageText.GetFont())

self.msgBoxWidth = 800 #pixels
rows = textWidth/self.msgBoxWidth
self.msgBoxHeight = (textHeightSingle * rows) + 20

self.MessageBoxText.SetMinSize((self.msgBoxWidth,self.msgBoxHeight))

self.msgSizer.Add( self.MessageBoxText, 1, wx.ALL|wx.EXPAND, 0 )
self.topSizer.Add(self.msgSizer, 1, wx.ALL|wx.EXPAND , 10)
self.SetSizer(self.topSizer)
self.Fit()
self.Center()

The scroll bar does allow me to see the entire text, but i was hoping to just resize the textctrl to see everything without the scrollbar and only need the scrollbar if its too big to fit the screen.

The setMinSize doesnt seem to be working because i can query self.messageBoxText.GetSize() and it ends up being shorter than i set it using SetMinSize.

i may have a listbox and bitmap in the topSizer too, but this is the most basic example i can think of.

Its got to be something simple. Any ideas on how to get what i want?

thanks

Upvotes: 1

Views: 1500

Answers (1)

RobinDunn
RobinDunn

Reputation: 6206

Estimating the height for multiline textctrls can be a tricky proposition, as there will be an unknown amount of pixels between lines, some unknown amount of space required above and below the body of text, etc. On top of that those values can vary across platforms, or even between different versions of the same platform.

Take a look at the wx.lib.expando module and the associated sample in the demo. It tries to deal with the issues identified above and usually does a pretty good job.

Upvotes: 1

Related Questions