PDA

View Full Version : Save QSettings when OK button is pressed



ecce
1st May 2016, 10:28
I'm in the process of creating a Settings dialog for my PyQt5 application. I have a button in the MainWindow toolbar that pops up a dialog box, containing a checkbox and a buttonBox (ui file). The idea is to load QSettings and show the appropriate settings (checked/unchecked). Changes can be made, and those are to be saved when you click the OK button.

So how do you do this? I thought that one way would be to "intercept" the OK clicking event and insert a few lines of code before the dialog is closed. I tried this:


class SettingsDialog(QDialog, Ui_SettingsDialog):
def __init__(self, parent=None):
super(SettingsDialog, self).__init__(parent)
self.setupUi(self)
self.settings = QSettings(QSettings.IniFormat, QSettings.SystemScope, 'someBiz', '__settings')
self.settings.setFallbacksEnabled(False)

self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)

self.addSettingCategories()


def addSettingCategories(self):
q = QTreeWidgetItem(self.settingsTree, ['General Settings'])
q.setIcon(0, QIcon('icons/32x32/gear_in.png'))


def accept(self):
# Insert QSettings save code here
print('accepted!')
super(SettingsDialog, self).accept()

That works, it prints out "accepted!" two times (button pressed and released?). My question is a bit general: Is this a suitable approach, or how do you usually do this? I guess another options is to return the QSettings object to the MainWindow and save it to file there?

anda_skoa
1st May 2016, 11:28
The only weird things is that you see the output twice, but otherwise that sounds good.

Overwriting accept() also allows you to do some final check on the value and, if necessary, keep the dialog open by just not calling the super class accept.

The only thing you probably need to do additionally is to make sure that other parts of the application which need those settings read them again.

Cheers,
_

d_stranz
2nd May 2016, 18:11
The only weird things is that you see the output twice, but otherwise that sounds good.

@ecce: Did you possibly make a connection in your ui code when you created the dialog in Qt Designer? That's the only thing I can think of that would cause the slot to be entered twice.