views:

941

answers:

2

I have a TextCtrl in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?

+1  A: 

Realize that most fonts are proportional, which means that each character may take a different width. WWW and lll are both 3 characters, but they will require vastly different sizes of text box. Some fonts, such as Courier, are designed to be fixed width and will not have this problem. Unfortunately you may not have any control over which font is selected in the text box.

If you still want to try this, the key is to get the width of a character in pixels, multiply it by the number of characters, then add some padding for the borders around the characters. You may find this to be a good starting point:

http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcgetpartialtextextents

or, as litb suggests:

http://docs.wxwidgets.org/2.4/wx_wxwindow.html#wxwindowgettextextent

Mark Ransom
+2  A: 

There doesn't seem to be a way. You can, however, use wxWindow::GetTextExtent. This is C++ code, but can be easily adapted to wxPython:

int x, y;
textCtrl->GetTextExtent(wxT("T"), &x, &y);
textCtrl->SetMinSize(wxSize(x * N + 10, -1));
textCtrl->SetMaxSize(wxSize(x * N + 10, -1));

/* re-layout the children*/
this->Layout(); 

/*  alternative to Layout, will resize the parent to fit around the new 
 *  size of the text control. */
this->GetSizer()->SetSizeHints(this);
this->Fit();

This is, you take the size of a reasonable width character (fonts may have variable width characters) and multiply it properly, adding some small value to account for native padding (say, 10px).

Johannes Schaub - litb