What if my text control doesnt match my string

When using a multi-line wx.TextCtrl, be aware of a small gotcha involving the way in which the text control stores the string. Internally, the multi-line string inside the wx.TextCtrl is stored using \n as the line separator. This is true no matter what the underlying operating system is, even though some systems use different character combinations as a line separator. When you retrieve the string using GetValue(), the native system's line separator is restored, so you don't have to worry about manual conversion backwards. The advantage is the text inside the control isn't dependent on any specific operating system.

The disadvantage is the line length and the line indexes inside the text control can be different than they are outside the text control. For example, if you are on a Windows system, where the line separator is \r\n, the length of the string as reported by GetValue() will be longer than the end of the string in the control as reported by GetLastPosition(). By adding the following two lines in listing 7.3, print "getValue", len(multiText.GetValue()) print "lastPos", multiText.GetLastPosition()

we would get the following results from a Unix operating system:

getValue 119 lastPos 119

and the following results from a Windows operating system:

getValue 121 lastPos 119

The implication is that you should never use the position indexes of a multi-line text control to refer back to the original string, rather, they should only be used as arguments to other methods of wx.TextCtrl. For a substring of the text within the control, use GetRange() or GetSelectedText(). Also do not cross the indexes in reverse; don't use indexes of the original string to refer back into the text control. Following is an example of the incorrect way to get 10 characters immediately after the insertion point:

aLongString = """Any old multi line string will do here. Just as long as it is multiline""" text = wx.TextCtrl(panel, -1, aLongString, style=wx.TE_MULTILINE) x = text.GetInsertionPoint()

selection = aLongString[x : x + 10] ### THIS WILL BE INCORRECT

The last line should be commented out for Windows or Mac systems because it uses x (the position of the insertion point in the text control) as an index for the original string. To return the correct characters in Windows or Mac systems, the last line should be written as follows:

Was this article helpful?

0 0

Post a comment