Search code examples
pythonwxpythonsaveitemslistctrl

wxPython - Save Items in ListCtrl


My question is if we can save the items on ListCtrl so everytime someone opens the application, the items are there and if the user removes it, it also removes from the configuration. I know that I can use wx.Config and I'm trying to accomplish using that but I don't know how to read it in a way to accomplish what I want.

So what I would like to know is a proper way to write/read the wx.Config in a way that everytime someone opens the application, the items from ListCtrl are there.

Thanks in advance.


Solution

  • Using wx.Config is very easy, just create config passing name of your app and add data e.g.

    config = wx.Config("StackOverflowTest")
    config.Write("testdata", "yes it works!")
    

    Now you can read it anytime

    config = wx.Config("StackOverflowTest")
    print config.Read("testdata")
    

    For saving list cntrl data I would suggest that you first read all data in a python list and pickle that list into config, next time read config, unpickle data and populate list, structure wise add functions like fillList/saveList so you can be sure reading writing part are nearby and similar.

    e.g. you can use this skeleton

    import wx
    import cPickle
    
    class MyListCtrl(wx.ListCtrl):
    
        def __init__(self, *args, **kwargs):
            wx.ListCtrl.__init__(self, *args, **kwargs)
            self.config = wx.Config("MykoolApp")
    
            self.fillist()
    
        def filllist(self):
             # load rows and check for error too, if no data
            data = self.config.Read("list_cntrl_data")
            rowList = cPickle.loads(data)
    
            for row in rowList:
                # add this row to list cntrl
                pass
    
        def savelist(self):
            rows = []
            for row in self:
                # add data to rows
                pass
    
            data =  cPickle.dumps(rows)
            self.config.Write("list_cntrl_data", data)
    
        def onchange(self):
            """
            on changes to list e.g. add delete call save list
            """
            self.savelist()