Qt 5.x 配置文件

发布于 2020-10-29  338 次阅读


#ifndef CONFIG_H
#define CONFIG_H

#include <QVariant>
#include <QSettings>

class Config
{
public:
    Config(QString qstrfilename = "");
    virtual ~Config(void);
    void Set(QString,QString,QVariant);
    QVariant Get(QString,QString);

private:
    QString m_qstrFileName;
    QSettings *m_psetting;
};

#endif // CONFIG_H
#include "config.h"

#include <QtCore/QtCore>
#include <QDebug>

Config::Config(QString qstrfilename)
{
    if (qstrfilename.isEmpty())
    {
        m_qstrFileName = QCoreApplication::applicationDirPath() + "/Config.ini";
    }
    else
    {
        m_qstrFileName = qstrfilename;
    }

    m_psetting = new QSettings(m_qstrFileName, QSettings::IniFormat);
   // qDebug() << m_qstrFileName;
}

Config::~Config()
{
    delete m_psetting;
    m_psetting = 0;
}

void Config::Set(QString qstrnodename,QString qstrkeyname,QVariant qvarvalue)
{
    m_psetting->setValue(QString("/%1/%2").arg(qstrnodename).arg(qstrkeyname), qvarvalue);
}

QVariant Config::Get(QString qstrnodename,QString qstrkeyname)
{
    QVariant qvar = m_psetting->value(QString("/%1/%2").arg(qstrnodename).arg(qstrkeyname));
    return qvar;
}
int main(int argc, char *argv[])
{
    QString qstrname = Config().Get("user","name").toString();
    QString qstrpasswd = Config().Get("user","password").toString();
    int nport = Config().Get("test","port").toInt();

    Config().Set("title", "timeout", 1024);
}