设置单元格属性会将新的GridCellAttr添加到GridCellAttrProvider的列表中。
随着列表的增长,查找单元格的特定属性(通过遍历列表并比较坐标)变得越来越慢。
您可以尝试通过实现自己的PyGridTableBase.SetAttr和GetAttr(例如使用dict)加快速度:
编辑:更新了代码以允许覆盖属性并模拟默认实现属性所有权。
class MyTable(wx.grid.PyGridTableBase):
atts = {}
def Hash(self,row,col):
#FIXME: assumes a constant number of rows and rows > cols
return col + row * self.GetNumberRows()
def SetAttr(self,attr,row,col):
HASH = self.Hash(row, col)
if HASH in self.atts:
# decrement usage count of existing attr
self.atts[HASH].DecRef()
#assign new attribute
self.atts[HASH] = attr
def GetAttr(self,row,col,kind):
HASH = self.Hash(row, col)
if HASH in self.atts:
attr = self.atts[HASH]
attr.IncRef() # increment reference count
return attr
return None要允许设置整个行和列,您还必须实现:
def SetRowAttr(self,attr,row):
for col in range(self.GetNumberCols()):
attr.IncRef() # increment reference count for SetAttr
self.SetAttr(attr,row,col)
attr.DecRef() # attr passed to SetRowAttr no longer needed
def SetColAttr(self,attr,col):
for row in range(self.GetNumberRows()):
attr.IncRef()
self.SetAttr(attr,row,col)
attr.DecRef()注意:将GridCellAttr传递给Set*Attr()时,默认实现将获取该属性的所有权。
要重新使用相同的属性(例如存储在类变量中),您必须使用Clone()或增加其使用计数(IncRef())
在将其传递给Set*Attr()方法之前(克隆可能会增加内存消耗)。
上面的示例没有正确删除属性:SetAttr()可以检查None attr并减少指定坐标处的ref计数,然后从dict中删除该条目。
SetCol/RowAttr()可以通过为行和列添加dicts来优化,类似于SetAttr()。然后,GetAttr()可以检查行中的现有条目和col dict,并使用单元格dict中的属性合并/覆盖属性(这是默认实现使用的原则)。为了正确清理字典,请在.clear()之前的每个条目上调用DecRef。
或者,您可以从wx.grid.GridCellAttrProvider派生并将其附加到PyGridTableBase.SetAttrProvider()。但是,这会阻止直接访问表。