Search code examples
c++qtqt5qsettings

Delete Key/Value Pair from configuration file qsetting


i am trying to search String in configuration file and if string match wants to delete key / value pair. i have getting qstringlist from file . as far as my tried code is

int main(int argc, char *argv[])
{
        QSettings* settings= new QSettings("/home/sidheshwar/Desktop/temp.txt", QSettings::IniFormat);

        settings->beginGroup("Profiles");
        const QStringList childKeys = settings->childKeys();

        QStringList Keys;
        QStringList values;
        QString user="db-host";
        QString tempUser;


        foreach (const QString &childKey, childKeys)
        {
            Keys << childKey;
            values << settings->value(childKey).toString();
        }

for(int i=0;i< Keys.length();i++){
    if(user == values.at(i)){
         qDebug() << " keys" << Keys[i] << endl;
tempUser=Keys[i];

    }
       qDebug() << " tempUser" << tempUser << endl;


}
      return 0;}

how can i use settings->remove(tempUser);


Solution

  • In the following example I show you an example of how to delete a data from the file that handles the configuration.

    temp.ini before the execution.

    [Profiles]
    key1=db-host
    key2=value2
    key3=value3
    

    main.cpp

    #include <QCoreApplication>
    #include <QSettings>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QSettings* settings= new QSettings("temp.ini", QSettings::IniFormat);
    
        settings->beginGroup("Profiles");
        const QStringList childKeys = settings->childKeys();
    
        QStringList Keys;
        QStringList values;
        QString user="db-host";
    
    
        foreach (const QString &childKey, childKeys)
        {
            Keys << childKey;
            values << settings->value(childKey).toString();
        }
    
        for(int i=0;i< Keys.length();i++){
            if(user == values.at(i)){
                qDebug() << " keys" << Keys[i];
                settings->remove(Keys[i]);
            }
            qDebug() << Keys[i] << values.at(i);
        }
    
    
        return a.exec();
    }
    

    Output:

    temp.ini after the execution

    [Profiles]
    key2=value2
    key3=value3