ini读写——Qt的QSettings
1、注意中文乱码的情况,如界面、qDebug、cmd、ini里
2、注释用英文分号,不用#
创建Widget界面项目,托放一个Label,核心代码如下
#include <QSettings> #include <QDebug> #pragma execution_character_set("utf-8") //防止中文乱码,如界面、qDebug、cmd窗口 Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); ui->label->setText("中文"); //指定ini文件,若无则自动创建 QSettings *pIni = new QSettings("config.ini", QSettings::IniFormat); //防止ini文件里中文乱码 pIni->setIniCodec("UTF-8"); //写 /* pIni->setValue("con/ip", "192.168.0.1"); pIni->setValue("con/name", "aa"); pIni->setValue("con/name2", "中文"); //pIni->beginGroup("con");//条目多用这种写法比较方便 //pIni->setValue("ip", "192.168.0.1"); //pIni->setValue("name", "aa"); //pIni->setValue("name2", "中文"); //pIni->endGroup(); pIni->setValue("port/int", "10"); pIni->setValue("port/double","0.1"); pIni->setValue("port/bool","true"); pIni->setValue("port/ports", "2222,111,33,444"); */ //读 int a=pIni->value("port/int","5").toInt(); double b=pIni->value("port/double","5.0").toDouble(); bool c=pIni->value("port/bool","false").toBool(); QString d=pIni->value("con/name2","默认值").toString(); //读取所有Key foreach(QString key,pIni->allKeys()) { qDebug() << key << pIni->value(key).toString(); } //读取某一组 pIni->beginGroup("port"); foreach(QString key,pIni->childKeys()) { qDebug() << key << pIni->value(key).toString(); } pIni->endGroup(); //读取所有组名 foreach(QString key,pIni->childGroups()) { qDebug() << key; } //查看结果 qDebug()<<a<<b<<c<<d; //释放,方便再指向另一个ini文件 delete pIni; pIni=nullptr; }