wxPython ListCtrl:写入彩色文本

3 投票
1 回答
4787 浏览
提问于 2025-04-17 04:12

我在尝试把字符串写入一个列表控件(ListCtrl),但是我对这个逻辑不是很明白。这是正确的方法吗?

    self.rightPanel = wx.ListCtrl(spliter, -1, style=wx.LC_REPORT)
    self.rightPanel.InsertColumn(0, 'LineNumber')
    self.rightPanel.InsertColumn(1, 'log')
    self.rightPanel.SetColumnWidth(0, 8)
    self.rightPanel.SetColumnWidth(1, 80)

def writeConsole(self,str):
    item = wx.ListItem()
    item.SetText(str)
    item.SetTextColour(wx.RED)
    item.SetBackgroundColour(wx.BLACK)                    
    index = self.rightPanel.GetItemCount()        
    self.rightPanel.InsertItem(item)
    self.rightPanel.SetStringItem(index, 0, str(index))
    self.rightPanel.SetStringItem(index, 1, item.GetText())

1- 为什么文本没有显示颜色?
2- 为什么在列表控件中显示文本有两种不同的方法?

   ListCtrl.InsertItem()
   ListCtrl.SetStringItem()

我觉得InsertItem只是把项目加载到列表中,然后用SetString来显示项目的内容。(不太确定)

1 个回答

6

SetTextColour()SetBackgroundColour() 是整个列表控件(listctrl)的方法,而不是针对单个项目的。对于单个项目,你应该使用(仅在报告模式下有效):

GetItemTextColour(idx_item)
SetItemTextColour(idx_item, col)

InsertItem(index, item)(这里的 item 是一个 wx.ListItem 的实例)是 InsertItem() 方法之一,用来在列表控件中添加一行新数据。

SetStringItem(index, col, label, imageId=-1)(其中 index 和 col 参数分别是单元格的行和列索引)可以用来设置任何选中列中的字符串。其他插入方法只适用于第一列。

参考书: wxPython in Action,作者:Noel Rappin 和 Robin Dunn。

撰写回答