I’ve been looking for a way to quickly get all the text and styles from a StyledTextCtrl.
The wxPython documentation says the GetCharacterPointer() method returns a MemoryBuffer object. I couldn’t find a description about the MemoryBuffer class but I noticed it has tolist() and tobytes() methods. When I call those methods I get the values I expect.
The wxPython documentation says the GetStyledText() method returns a MemoryBuffer of cells. The Scintilla documentation says it should use two bytes for each cell, with the character at the lower address of each pair and the style byte at the upper address.
When I tested this I did get twice as many bytes from GetStyledText() compared to GetCharacterPointer() however those bytes didn’t appear to bear any relation to the characters or styles in the STC. What’s more the values were different every time I ran the program!
Here is a simple program that just puts a single upper-case ‘A’ in an STC (without explicitly setting a style) and then calls the 2 methods:
import wx import wx.stc as stc class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.SetSize((400, 300)) self.SetTitle("Test GetStyledText()") self.main_panel = wx.Panel(self, wx.ID_ANY) main_sizer = wx.BoxSizer(wx.VERTICAL) self.stc = stc.StyledTextCtrl(self.main_panel, wx.ID_ANY) main_sizer.Add(self.stc, 1, wx.EXPAND, 0) self.main_panel.SetSizer(main_sizer) self.Layout() self.stc.AddText("A") cp = self.stc.GetCharacterPointer() c_list = cp.tolist() print(len(c_list)) print(c_list) print(cp.tobytes()) print() st = self.stc.GetStyledText(0, self.stc.GetLastPosition()) t_list = st.tolist() print(len(t_list)) print(t_list) print(st.tobytes()) print() style = self.stc.GetStyleAt(0) print(style) class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(None, wx.ID_ANY, "") self.SetTopWindow(self.frame) self.frame.Show() return True if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Here are the results from running it once:
1  b'A' 2 [80, 238] b'P\xee' 0
Is this a bug, or am I not doing it right?
I am running on Python 3.8.10 + wxPython 4.1.1 gtk3 (phoenix) wxWidgets 3.1.5 + Linux Mint 20.2