如何清除具有透明背景的自定义wx.StaticText的设备上下文?

时间:2019-07-22 19:15:11

标签: python wxpython wxwidgets

我想实现一个自定义绘制的wx.StaticText,它具有在其周围绘制焦点Rect的功能。

如果我使用wx.PaintDC,它可以正常工作,但是它似乎不支持背景透明性,所以我切换到wx.GCDC,但是我没有找到清除前一个DC的方法,因此焦点反应始终显示:

import wx


class MyStatic(wx.StaticText):

    def __init__(self, parent, id, label=''):
        wx.StaticText.__init__(self, parent, id, label, wx.DefaultPosition, wx.DefaultSize,
                               style=wx.CLIP_CHILDREN | wx.TRANSPARENT_WINDOW)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda: None)
        self.Bind(wx.EVT_SIZE, self.on_Size)
        self.custom_rect = False

    def on_paint(self, event):
        print("On_Paint")

        # This one works, but does not support background transparency
        #dc = wx.PaintDC(self)

        dc = wx.GCDC(wx.PaintDC(self))

        dc.SetTextForeground(self.GetForegroundColour())
        dc.SetTextBackground(self.GetBackgroundColour())
        dc.SetBackgroundMode(wx.TRANSPARENT)
        dc.SetBackground(wx.Brush(wx.YELLOW, style=wx.BRUSHSTYLE_TRANSPARENT))

        # The clear here does not really clear the previous DC
        dc.Clear()

        dc.SetFont(self.GetFont())
        dc.DrawText(self.GetLabel(), 0, 0)

        if self.custom_rect:
            print("printing the rect")
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.BLACK_DASHED_PEN)
            size = self.GetSize()
            dc.DrawRectangle(0, 0, size.GetWidth(), size.GetHeight())

        event.Skip()

    def on_erease(self, event):
        print("on_erease")
        event.Skip()

    def on_Size(self, event):
        print("on_Size")
        self.Refresh()
        event.Skip()


class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, pos=(150, 150), size=(350, 200))

        self.SetBackgroundColour(wx.GREEN)

        box = wx.BoxSizer(wx.VERTICAL)

        self.m_text = MyStatic(self, -1, "Test label !")
        self.m_text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL))
        box.Add(self.m_text, 0, wx.ALL, 10)

        m_btn = wx.Button(self, -1, "Toggle custom_rect")
        m_btn.Bind(wx.EVT_BUTTON, self.on_btn_clicked)
        box.Add(m_btn, 0, wx.ALL, 10)

        self.SetSizer(box)

    def on_btn_clicked(self, event):
        self.m_text.custom_rect = not self.m_text.custom_rect
        self.m_text.Refresh()


app = wx.App(redirect=False)  # Error messages go to popup window
top = Frame("test custom StaticText")
top.Show()
app.MainLoop()

非常感谢您的帮助。

0 个答案:

没有答案