How to save and load QListWidjet contents to/from

2019-09-02 03:28发布

问题:

I've got a QListWidget in my PyQt4 app. It contains folders paths. I want to save its contents to QSettings and load them later. I used this code to do this:

def foldersSave(self):
    folders = {} '''create dict to store data'''
    foldersnum = self.configDialog.FolderLIST.count() '''get number of items'''
    if foldersnum:
        for i in range(foldersnum):
            folders[i] = self.configDialog.FolderLIST.item(i).text() '''save items text to dict'''
        return str(folders) '''return string of folders to store in QSettings'''
    return None

But if I make so folders paths are stored in config file like:

musicfolders={0: PyQt4.QtCore.QString(u'/home/sam/Ubuntu One')}

So I have no idea how to load them then. I've tryed something like this in different variants:

def foldersLoad(self):
    folders = eval(self.tunSettings.value('musicfolders').toString())

It returns error:

TypeError: eval() arg 1 must be a string or code object

It looks like I just need to save data some other way then I do now. Gooled a lot, but have no clue. I'm sure the answer is trivial, but I'm stuck.

回答1:

The solution is very simply. I were to use QStringList.

def foldersSave(self):
    folders = QtCore.QStringList()
    foldersnum = self.configDialog.FolderLIST.count()
    if foldersnum:
        for i in range(foldersnum):
            print (i, " position is saved: ", self.configDialog.FolderLIST.item(i).text())
            folders.append(self.configDialog.FolderLIST.item(i).text())
        return folders
    return None

and load

def foldersLoad(self):
    folders = QtCore.QStringList()
    folders = self.tunSettings.value('musicfolders', None).toStringList()
    if folders.count():
        foldersnum = folders.count()
        for i in range(foldersnum):
            self.configDialog.FolderLIST.addItem(folders.takeFirst())