wxpython学习笔记(推荐查看)

2019-10-06 14:22:11丽君

        for col, text in enumerate(data.columns):
            self.list.InsertColumn(col, text)

        # add the rows
        for item in data.rows:
            index = self.list.InsertStringItem(sys.maxint, item[0])
            for col, text in enumerate(item[1:]):
                self.list.SetStringItem(index, col+1, text)

            # give each item a random image
            img = random.randint(0, il_max)
            self.list.SetItemImage(index, img, img)

        # set the width of the columns in various ways
        self.list.SetColumnWidth(0, 120)
        self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
        self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE)
        self.list.SetColumnWidth(3, wx.LIST_AUTOSIZE_USEHEADER)


app = wx.PySimpleApp()
frame = DemoFrame()
frame.Show()
app.MainLoop()

对于ListCtrl控件,我要补充的几个地方是:

1. 如何获取选中的项目?

 最常用的方法就是获取选中的第一项:GetFirstSelected(),这个函数返回一个int,即ListCtrl中的项(Item)的ID。

 还有一个方法是:GetNextSelected(itemid),获取指定的itemid之后的第一个被选中的项,同样也是返回itemid。

 通过这两个方法,我们就可以遍历所有选中的项了:


GetNextSelecteditemid = self.list.GetFirstSelected()
while itemid <> -1:
        #Do something
        itemid = self.list.GetNextSelected(itemid)

如果要获取某一行,某一列的值,则通过下面的方法:


#获取第0行,第1列的值
itemtext = self.list.GetItem(0, 1).Text

2. 如何在选定项后添加右键菜单?

在__init__函数中,添加如下的事件绑定:
self.list.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)然后,添加OnContextMenu方法:


def OnContextMenu(self, event):
        if not hasattr(self, "popupStop"):
            self.popupStop = wx.NewId()
            self.popupPropery = wx.NewId()
            self.Bind(wx.EVT_MENU, self.OnPopupStop, id = self.popupStop)