Search code examples
wxpythonsubscriptsuperscriptrichtextctrl

Superscript in wxPython RichTextCtrl


I am trying to get wxPython RichTextCtrl to display superscripts. I have seend some wxWidgets code at

http://wxwidgets.10942.n7.nabble.com/rich-text-and-font-attributes-td23557.html

and also seen the documentation at

https://wxpython.org/Phoenix/docs/html/wx.TextAttr.html#wx.TextAttr.SetTextEffects

So far, I have got this and it's not working

attr = wx.richtext.RichTextAttr()
attr.SetTextEffects (wx.TEXT_ATTR_EFFECT_SUPERSCRIPT)
attr.SetTextEffectFlags (wx.TEXT_ATTR_EFFECTS)
#attr.SetTextEffectFlags (wx.TEXT_ATTR_EFFECT_SUPERSCRIPT)
attr.SetFlags (wx.TEXT_ATTR_EFFECTS)
self.myRichTextCtrl.SetStyle (currentPos, currentPos+len(value1)-1, attr)
self.myRichTextCtrl.WriteText (myString)

I know there's a fancytext widget, but it's not practical to switch to fancytext at this point.

Any help would be much appreciated!


Solution

  • With SetStyle you are applying attributes to text positions that you haven't written yet.

    There is an option SetBasicStyle and SetDefaultStyle which allow you to set the attributes for the whole document or from now on.

    Here is a working example.

    import wx
    import wx.richtext as rt
    class MainFrame(wx.Frame):
    
        def __init__(self):
            wx.Frame.__init__(self, None, title='Test RichText Superscript')
            self.panel = wx.Panel(self)
    
            self.rtc1 = rt.RichTextCtrl(self.panel,pos=(10,10),size=(350,90),style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER|wx.FONTFAMILY_DEFAULT|wx.TEXT_ATTR_FONT_FACE)
            self.rtc2 = rt.RichTextCtrl(self.panel,pos=(10,110),size=(350,90),style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER|wx.FONTFAMILY_DEFAULT|wx.TEXT_ATTR_FONT_FACE)
    
            self.Show()
    
            attr_super = wx.richtext.RichTextAttr()
            attr_super.SetTextEffects(wx.TEXT_ATTR_EFFECT_SUPERSCRIPT)
            attr_super.SetFlags(wx.TEXT_ATTR_EFFECTS)
            attr_super.SetTextEffectFlags(wx.TEXT_ATTR_EFFECT_SUPERSCRIPT)
            self.rtc1.WriteText("Is this super?")
            self.rtc1.SetStyle (7, 13, attr_super)
    
            attr_sub = wx.richtext.RichTextAttr()
            attr_sub.SetTextEffects(wx.TEXT_ATTR_EFFECT_SUBSCRIPT)
            attr_sub.SetFlags(wx.TEXT_ATTR_EFFECTS)
            attr_sub.SetTextEffectFlags(wx.TEXT_ATTR_EFFECT_SUBSCRIPT)
            self.rtc1.AppendText ("\nIs this sub?")
            self.rtc1.SetStyle (23, 26, attr_sub)
            self.rtc1.AppendText ("\nIs this normal?")
    
            self.rtc2.WriteText("Is this super?")
            self.rtc2.SetDefaultStyle(attr_super)
            self.rtc2.WriteText("\nIs this super?")
    
    
    
    if __name__ == '__main__':
        app = wx.App()
        frame = MainFrame()
        app.MainLoop()
    

    enter image description here