Here is the demo code, I wrote comments in the code:
Environment is Python 3.8 and wxpython-4.2.1. But the other versions behave the same.
import wx
import wx.stc as stc
class MyTextCtrl(stc.StyledTextCtrl):
def __init__(self, parent):
stc.StyledTextCtrl.__init__(self, parent)
def SetUnicodeSelection(self, p1, p2):
# This is my user define function. I convert the unicode text range into bytes range.
text = self.GetValue()
p1, p2 = (len(text[:p].encode()) for p in (p1, p2)) # unicode index -> bytes index
self.SetSelection(p1, p2)
if __name__ == '__main__':
app = wx.App()
frame = wx.Frame(None, -1, 'Test Unicode Selection')
text = MyTextCtrl(frame)
# Initial some unicode text
text.SetValue(
'有日月朝暮悬,有鬼神掌着生死权。\n'
'天地也,只合把清浊分辨,可怎生糊突了盗蹠颜渊?\n'
'为善的受贫穷更命短,造恶的享富贵又寿延!\n'
'天地也,做得个怕硬欺软,却原来也这般顺水推船。\n'
'地也,你不分好歹何为地?天也,你错勘贤愚枉做天!\n'
'哎,只落得两泪涟涟。\n'
)
# The text of ",有鬼神掌着生死权" is the 6 to 15 chars of the demo text.
# If I select the range of 6 to 15, it will be wrong.
# How can I select this text by builtin function, but not my user define function?
# text.SetSelection(6, 15) # <- this selection will be wrong
text.SetUnicodeSelection(6, 15) # <- use user define function will be correct, and the definition is above
frame.Center()
frame.Show()
app.MainLoop()