是否有直接的方法来设置wx.TextCtrl大小的字符而不是像素?

时间:2018-03-24 18:10:46

标签: wxpython wxwidgets wxpython-phoenix

wx.TextCtrl的构造函数采用wx.Size参数,以像素为单位。通常,我不想指定多行TextCtrl的大小(以像素为单位),而是指定它可以在不滚动的情况下显示多少个字符。我发现多行TextCtrls通常是我窗口中的主要组件,因此Sizer的拉伸不是一种选择。

关于如何执行此操作的wxPython Phoenix文档contains a hint,但这对于单行控制的短文本更有意义。

我已经开始使用此实用程序方法:

def _set_textctrl_size_by_chars(self, tc, w, h):
    sz = tc.GetTextExtent('X')
    sz = wx.Size(sz.x * w, sz.y * h)
    tc.SetInitialSize(tc.GetSizeFromTextSize(sz))

以及这样的代码:

tc = wx.TextCtrl(self, style=wx.TE_MULTILINE)
self._set_textctrl_size_by_chars(tc, 80, 20)

这有效,但我认为这是一个黑客。我查看了文档,但没有找到任何其他方法。

我知道字体通常不是等宽字体,并且使用'X'作为代表字符宽度是不精确的,但是它足够好用于我的使用。不过,似乎应该有一些方法可以直接使用wx库。

1 个答案:

答案 0 :(得分:0)

Using something like text.GetSizeFromTextSize(text.GetTextExtent("99999").x) is indeed the best way to size the text control to fit exactly 5 digits (e.g. a ZIP code in some localities). Notice that this is slightly better than your code because the width of 80 "X"s is not necessarily quite the same as 80 times the width of a single "X". And I'd also recommend using "M" or "W" which can be noticeably wider than "X" in some fonts, but this is not going to changes matters much.

We thought about adding a helper method doing this and it might indeed be useful, but, again, this still won't make things as simple as you'd like because you really need to specify the characters you want to use: "W" for letters, "9" for digits and maybe something like "x" if you want the control to be wide enough to fit the given number of characters on average instead of being wide enough to guarantee fitting the given number of the widest characters because the difference may be noticeable.

The main place where we could make life simpler would be at XRC level and this would be worth doing ("just" a question of time...), but for the code I really don't think we can make things much simpler than what they're now.