Qt | How to load/save .ini File with Qt

本文作为个人笔记用。文章出处:http://ohurochan.jp/blog/en/development/qt-how-to-loadsave-ini-file-with-qt

This note is written for setting/getting parameter of App to/from “.ini” file.

[h1]sample.ini

# this is a Sample ini file
 [GROUPA]
 PARAM1 = 10
 PARAM2 = 20

 [GROUPB]
 PARAM1 = 30
 PARAM2 = 40
 PARAM3 = ABC

[h1] how to load params from .ini

        // Load Application params from ini file
        QSettings settings( iniFileName, QSettings::IniFormat );

        settings.beginGroup("GROUPA");
        int param1 = settings.value("PARAM1").toInt();
        int param2 = settings.value("PARAM2").toInt();
        settings.endGroup();

        settings.beginGroup("GROUPB");
        int param1 = settings.value("PARAM1").toInt();
        int param2 = settings.value("PARAM2").toInt();
        int param2 = settings.value("PARAM3").toString();
        settings.endGroup();

This code will get

GROUPA.param1 = 10
GROUPA.param2 = 20
GROUPB.param1 = 30
GROUPB.param2 = 40
GROUPB.param3 = ABC

Get all sections

    QSettings settings( "sample.ini", QSettings::IniFormat );
    QStringList keys = settings.childGroups();
    qDebug() << "keys == " << keys;

This code will get

keys ==  ("GROUPA", "GROUPB")

Delete group

    settings.remove(keys.at(1));
    keys = settings.childGroups();
    qDebug() << "keys == " << keys;

This code will get

keys ==  ("GROUPA")

The sample.ini will become

# this is a Sample ini file
 [GROUPA]
 PARAM1 = 10
 PARAM2 = 20

[h1] how to save params to .ini

        // Load Application params from ini file
        QSettings settings( iniFileName, QSettings::IniFormat );

        settings.beginGroup("GROUPA");
        settings.setValue("PARAM1", 10);
        settings.setValue("PARAM2", 20);
        settings.endGroup();

        settings.beginGroup("GROUPB");
        settings.setValue("PARAM1", 30);
        settings.setValue("PARAM2", 40);
        settings.setValue("PARAM3", "ABC");
        settings.endGroup();

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,189评论 0 6
  • 42-Coldplay 他站在地铁的终点站,等待末班车驶来。 这是他的工作,昼伏夜出,像极了密涅瓦的猫头鹰,在黄昏...
    宸琰阅读 294评论 0 0
  • S.O.L.I.D是面向对象设计和编程(OOD&OOP)中几个重要编码原则(Programming Pricipl...
    ch32053阅读 3,968评论 0 10
  • 我喜欢玫瑰,喜欢它的红色,虽然它有刺;我喜欢蓝天,喜欢它那种湛蓝,虽然它会乌云密布;我喜欢夏天梧桐的绿油油,虽然它...
    OC老陈阅读 305评论 0 0