Opening a QDialog and saving last state

断了今生、忘了曾经 提交于 2019-12-02 02:11:57
Brendan Abel

There are a couple ways you could persist this data Generally, to persist data across sessions, you use QSettings and load the data in the __init__ and save it in the closeEvent method

Generally it looks something like this. This also assumes your using the v2 version of the QVariant api; otherwise, the results returned from QSettings.value is going to be a QVariant and you'll need to cast it to the appropriate python type. If you're using a recent version of PyQt then you should be on v2, but if not you can force it by sticking this at the top of your file

import sip
sip.setapi('QVariant', 2)
sip.setapi('QString', 2)


class MyDialog(QDialog):

    def __init__(self, parent):
        super(MyDialog, self).__init__(parent)
        self.myvalue = 10
        self.restoreSettings()

    def closeEvent(self, event):
        self.saveSettings()
        super(MyDialog, self).closeEvent(event)

    def saveSettings(self):
        settings = QSettings('myorg', 'myapp')
        settings.setValue('myvalue', self.myvalue)

    def restoreSettings(self):
        settings = QSettings('myorg', 'myapp')
        self.myvalue = settings.value('myvalue', self.myvalue)

EDIT:

The error in your code is caused by this:

self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.closeEvent)

You shouldn't be calling or connecting to closeEvent directly. Instead, you should connect to .close or .accept

self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.accept)

You need to instantiate the ConfigurePort class then the self.configurePortDialog object should keep consistent. You will need to make sure if you have the user enter data that a cancel does not store the data and that an "ok" stores the data, but I not sure what you are putting in your dialog.

class A (QMainWindow):
  def __init__(self):
    QMainWindow.__init__(self)

    #I create a QPushButton to open the QDialog
    self.button = QPushButton("Open Dialog")
    self.button.on_clicked(self.OpenDialog)
    self.configurePortDialog = configurePort.ConfigurePort(parent=self)
    self.configurePortDialog.accepted.connect(self.get_data)

    #This is the method to open the QDialog which is in another module
  def OpenDialog(self, event):
     self.configurePortDialog.show()

  @QtCore.Slot()
  def get_data(self)
    text = self.configurePortDialog.retrieve_data()
    print text
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!