Saving Settings and Playlist on Exit

Ok, this a triky one. In the main form's constructor we have to add the folowing code at the end.
class MainForm(QtGui.QWidget):
 def __init__(self):
[.........................]
    self.settings = None
    self.readSettings()
    self.play_list.reset()

Then we add 2 methods, one for reading and one for writing settings:

def writeSettings(self):
 self.settings = QtCore.QSettings("Kodekraft", "player")
 self.settings.beginGroup("MainForm")
 self.settings.setValue("size", self.size())
 self.settings.setValue("pos", self.pos())
 self.settings.endGroup()
 if self.play_list.rnd:
   self.settings.setValue("playlist/rnd", 1)
 else:
   self.settings.setValue("playlist/rnd", 0)
 self.settings.beginWriteArray("contents")
 for i in range(len(self.play_list.contents)):
   self.settings.setArrayIndex(i)
   self.settings.setValue("code",self.play_list.contents[i].code)
   self.settings.setValue("name",self.play_list.contents[i].name)
 self.settings.endArray()

def readSettings(self):
 self.settings = QtCore.QSettings("Kodekraft", "tubeplayer")
 self.settings.beginGroup("MainForm")
 self.resize(self.settings.value("size", QtCore.QSize(400, 400)))
 self.move(self.settings.value("pos", QtCore.QPoint(200, 200)))
 self.settings.endGroup()
 if int(self.settings.value("playlist/rnd", 0)) == 0:
   self.play_list.rnd = False
 else:
   self.play_list.rnd = True
 self.ui.shuffleButton.setFlat(self.play_list.rnd)
 size = self.settings.beginReadArray("contents")
 for i in range(size):
   self.settings.setArrayIndex(i)
   code, name = self.settings.value("code"), self.settings.value("name")
   self.play_list.contents.append(TubeItem(code, name))
 self.settings.endArray()
 self.play_list.reset()

def closeEvent(self, event):
 self.writeSettings()
 event.accept()

The QtCore.QSettings object save data about the app in a "cross-platform way". This means
that in windows it edits the registry entry, in linux the INI file, and the XML preferences files
on Mac OS X.

The 'writeSettings()' method gets called on the 'closeEvent'.  It will save sattings about the
window size, position, if shuffle on/off and the playlist. This information is read in the main
form constructor.

Back to Contents

Advertisements
This entry was posted in PySide, Python, TubePlayer and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s