我试图从一个QMainWindow
打开QDialog
,在关闭`QDialog之后,如果我需要再次打开它,它必须打开并显示与我关闭时相同的信息。在
以下是QMainWindow
的代码:
class A (QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
#I create a QPushButton to open the QDialog
self.axes1 = self.figure_canvas.figure.add_axes ([0.8, 0.01, 0.19, 0.05])
self.button = QPushButton(self.axes1,"Open Dialog")
self.button.on_clicked(self.OpenDialog)
#This is the method to open the QDialog which is in another module
def OpenDialog(self, event):
text = configurePort.ConfigurePort.retrieve_data(self)
print text
这段代码的作用是在我的QMainWindow
中创建一个按钮,当我单击它时,它会打开一个在另一个模块中创建的QDialog
。这是QDialog
的代码:
在closeEvent
方法中,我需要编写必要的代码,这样我就可以关闭窗口,然后使用打开窗口时使用的相同按钮,使用关闭窗口时显示的最后一个信息再次打开它。在
我尝试过使用QSettings
,但它没有起作用(也许我用错了)。我也尝试了show()
和hide()
类,但是没有用。希望你能帮助我。在
我编辑了上面的代码。为了更好的理解,我添加了一些方法。因此,我打开名为ConfigurePort
的QDialog
,它显示了以下内容:
红色圆圈围绕着港口的名称。它显示在一个QLabel
中,我从QDialog
中获取此文本,然后在关闭QDialog
时打印它。我之所以这么做,是因为我之前问过一个问题,这个问题在这个链接中:
Getting data from child using PyQt
上面代码中显示的check_port
方法打开了另一个工作良好的QDialog
。有了这个,我可以在我的电脑上选择我需要的端口。所以,这并不重要。在
因此,在关闭QDialog
(并选择例如“COM3”,如图所示),我需要再次打开它,并查看关闭之前显示的相同信息。在
我尝试使用QSettings
添加以下行:
self.settings = QSettings("MyCompany", "MyApp")
if not self.settings.value("windowsState") == None:
self.restoreState(self.settings.value("windowState"))
但正如我之前所说,我认为我没有正确使用它,但我希望我能用更简单的方法来解决这个问题。在
感谢@Brendan Abel的帮助,我有了这个代码:
class ConfigurePort(QDialog):
def __init__(self, parent):
super(ConfigurePort, self).__init__(parent)
uic.loadUi("configurePort.ui", self)
self.myValue = 10
self.restoreSettings()
self.connect(self.btn_checkconn, SIGNAL("clicked()"), self.check_ports)
self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(self.close)
self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.closeEvent)
self.iniUi()
def check_ports(self):
pass
def iniUi(self):
pass #I just create some QLabels in here
@classmethod
def retrieve_data(cls, parent = None):
dlg = cls(parent)
dlg.exec_()
text = dlg.getPortText()
return text
def closeEvent(self, event):
self.saveSettings()
super(QDialog,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)
这给了我一个错误:TypeError: QWidget.closeEvent(QCloseEvent): argument 1 has unexpected type 'bool'
我知道我错过了什么,但我看不见。在
通常有两种方法可以持久化此数据,要跨会话持久化数据,可以使用
QSettings
并在__init__
中加载数据,并将其保存在closeEvent
方法中一般看起来像这样。这还假设您使用的是
v2
版本的QVariant
api;否则,QSettings.value
返回的结果将是QVariant
,您需要将其转换为适当的python类型。如果您使用的是PyQt
的最新版本,那么您应该在v2
,but if not you can force it上粘贴这个文件编辑:
代码中的错误是由以下原因引起的:
^{pr2}$您不应该直接调用或连接到}
closeEvent
。相反,您应该连接到.close
或{您需要实例化
ConfigurePort
类,然后self.configurePortDialog
对象应该保持一致。如果你让用户输入数据,你需要确保取消不会存储数据,“确定”会存储数据,但我不确定你在对话框中输入了什么。在相关问题 更多 >
编程相关推荐