QML中使用Settings

对于大多数应用程序而言,数据存储是必须的。Qt中对于本地存储,C++中提供了基于本地数据文件/注册表的类QSettings,对于Qt Quick来说,虽然可以使用QSettings处理例如ini类型的配置文件,然后将数据映射到QML中,但是一般的小型应用来说,这样做是影响开发效率的,因此使用Qt Quick中提供的类Settings。

使用方法:

1、在QML中导入类:

import Qt.labs.settings 1.0

 2、在main.cpp中设置程序注册表信息:

 QApplication app(argc, argv);
 app.setOrganizationName("YZTC Company");
 app.setApplicationName("YZTC Application");

3、在QML需要保存的地方使用Settings:

Settings{
   id:settings
   property var jd : 102.6394
   property var wd : 24.9394
}
TextInput {
   id: textInput_JD
   height: 20
   text: settings.jd
   clip: true
   anchors.rightMargin: 5
   anchors.leftMargin: 5
   anchors.verticalCenter: parent.verticalCenter
   anchors.right: parent.right
   anchors.left: parent.left
   font.pointSize: 12
}
TextInput {
   id: textInput_WD
   height: 20
   text: settings.wd
   cursorVisible: true
   clip: true
   anchors.left: parent.left
   anchors.leftMargin: 5
   font.pointSize: 12
   anchors.right: parent.right
   anchors.verticalCenter: parent.verticalCenter
   anchors.rightMargin: 5
}
Button {
   id: button4
   width: 100
   text: qsTr("保存数据")
   onClicked: {
       settings.jd = textInput_JD.text
       settings.wd = textInput_WD.text
   }
}

程序关闭后,再次启动程序时,上次保存的数据信息就会直接在文本框中了。

数据在注册表中存储的位置:HKEY_CURRENT_USER\Software\YZTC Company\YZTC Application

猜你喜欢

转载自blog.csdn.net/zjgo007/article/details/107018447