SystemSettings
SystemSettings对象允许程序查询系统默认的颜色和字体信息。在创建自定义绘制控件时,能够知道这些信息是非常有用的。它使得使用和系统组件正在使用的一样的颜色和字体称为可能。这使自定义的控件或窗口装饰和系统组件无违和,看起来和其他原始的系统组件一样共享同一窗口。
示例说明
创建一个控件类似StaticText,但是有一个和Frame的标题栏相似的标题。
#-*-coding: UTF-8 -*-
#------------------------------------------------------
#Purpose: nothing....
#Author: 阿Bin先生
#Created: 2017年5月21日
#------------------------------------------------------
import wx
class CaptionBox(wx.PyPanel):
def __init__(self, parent, caption):
super(CaptionBox, self).__init__(parent, style=wx.NO_BORDER)
# Attributes
self._caption = caption
self._csizer = wx.BoxSizer(wx.VERTICAL)
# Setup
self.__DoLayout()
# Event Handlers
self.Bind(wx.EVT_PAINT, self.OnPaint)
def __DoLayout(self):
msizer = wx.BoxSizer(wx.HORIZONTAL)
self._csizer.AddSpacer(12) # extra space for caption
msizer.Add(self._csizer, 0, wx.EXPAND|wx.ALL, 8)
self.SetSizer(msizer)
def DoGetBestSize(self):
size = super(CaptionBox, self).DoGetBestSize()
# Compensate for wide caption labels
tw = self.GetTextExtent(self._caption)[0]
size.SetWidth(max(size.width, tw+20))
return size
def AddItem(self, item):
"""Add a window or sizer item to the CaptionBox"""
self._csizer.Add(item, 0, wx.ALL, 5)
def OnPaint(self, event):
"""Draws the Caption and border around the controls"""
dc = wx.PaintDC(self)
# Get the working rectangle we can draw in
rect = self.GetClientRect()
# Get the system color to draw the caption
ss = wx.SystemSettings
color = ss.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
txtcolor = ss.GetColour(wx.SYS_COLOUR_CAPTIONTEXT)
dc.SetTextForeground(txtcolor)
# Draw the border
rect.Inflate(-2, -2)
dc.SetPen(wx.Pen(color))
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawRectangleRect(rect)
# Add the Caption
rect = wx.Rect(rect.x, rect.y,
rect.width, 16)
dc.SetBrush(wx.Brush(color))
dc.DrawRectangleRect(rect)
rect.Inflate(-5, 0)
dc.SetFont(self.GetFont())
dc.DrawLabel(self._caption, rect, wx.ALIGN_LEFT)
class MyFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
super(MyFrame, self).__init__(parent, *args, **kwargs)
# Attributes
self.Panel = wx.Panel(self)
box = CaptionBox(self.Panel, "CaptionBox")
box.SetSize([100, 100])
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="DrawShapes",size = [500, 500])
self.SetTopWindow(self.frame)
self.frame.Show()
return True
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
运行结果:
书中的截图更表达清楚:
示例分析
在OnPaint方法里,利用从SystemSettings单实例获得的颜色,绘制控件标题的背景颜色和文本颜色。