Search code examples
pythonwxpythonwxwidgets

wxPython ,Change the background colour of a StyledTextCtrl


I tried (but nothing happens)

    self.txt.SetBackgroundColour ((255,0,0))

As said in the title I'm trying to change the background colour StyledTextCtrl. Does anyone know a method that could be used? I've checked the API docs but I couldn't seem to find one, http://wxpython.org/docs/api/wx.stc.StyledTextCtrl-class.html

(by background colour, I mean the whole writing area, of course)

Does anyone know a way I could do this?

EDIT:

The background doesn't change in the following code

import wx
import wx.stc

app = wx.App(redirect=True)
top = wx.Frame(None, title="StyledTXTCtrl", size=(300,200))
txt=wx.stc.StyledTextCtrl(top)
txt.SetBackgroundColour((255,255,0))
txt.Refresh()
top.Show()
app.MainLoop()

Solution

  • My first reaction was to call txt.Refresh() because I had a similar experience using wx.TextCtrl where the background colour did not update and the Refresh() call forced a redraw. However, it seems that approach was incorrect.

    After reviewing the StyledTextCtrl API, it seems like SetBackground() is not the function you want. My understanding is that because STCs can have multiple styles in the same box, the individual text styles take precedence over the STC's settings.

    After some research I found the StyleSetBackground() function. This modifies the default style such that the background will be red, effectively setting the background to red. You need to call it like this:

    txt.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, (255,0,0))
    

    Just remember, if you use multiple styles you may need to make invoke this method for each one.

    ---EDIT---
    I forgot to check my code code by entering some text. It turns out that if all you do is call SyleSetBackground() like I suggest above, when you enter text the background of the entered text is still white, not the expected red.

    A bit more research and I've discoved this is easily fixed by calling the following code after setting the background colour:

    txt.StyleClearAll()
    

    My guess is that when you create the StyledTextCtrl, it sets the text style equal to wx.stc.STC_STYLE_DEFAULT. So far so good. However, after this point we change the value of the default style (by making the background red) so now the text style and the default style are different. Therefore, we need to call StyleClearAll() to reset ALL STYLES back to the default style (which now has a red background).