Qsetting本地缓存PC端数据

  • Post author:
  • Post category:其他


在做pc端应用的时候,有时候需要保存一些数据,比如用户登录信息做个本地缓存

实现方式有很多种,一种用qsetting,一种用QFile本地文件读写,还有就是用数据库了

这里说前面两种

首先QSettings

在网上搜索一下QSetting的使用往往会告诉你这样使用

QSettings settings("userconfig.ini", QSettings::IniFormat);

setting后面指定文件名字,以及文件格式,然后这个文件就创建在编译后的应用执行文件同级目录下了

如果是Mac端

就在contents目录下,如图

文件创建后就是保存数据

            settings.setValue("userinfo/companyids", companyids);
            settings.setValue("userinfo/usernames", usernames);
            settings.sync();

正常使用的话这样确实没问题的,但是有些特殊应用,需要管理员权限的,在Mac端这样写就会遇到麻烦,因为Contents目录下的文件点击运行后没有权限读写,文件会被锁定,

Windows没影响

这时候,QSettings的初始化就要这样写,不需要指定文件名和文件格式,直接把数据保存到钥匙串,

QSettings settings

然后读取数据

    companyids = settings.value("userinfo/companyids").toStringList();
    usernames = settings.value("userinfo/usernames").toStringList();

搞定

第二种方法就是用QFile 读写,细节就不说了,直接上代码

#include "BsUtil.h"
#include "logger.h"
/**
 * @brief BsJsonObjToStr
 * @param jObj
 * @return empty string when the source object is empty
 */
QString BsJsonObjToStr(const QJsonObject &jObj ){
    if(jObj.isEmpty()){
        return "";
    }

    QJsonDocument jDoc;
    jDoc.setObject(jObj);

    return (QString)jDoc.toJson();
}

/**
 * @brief BsLocalDataUserRead
 * find a user from local file data
 * @param strUser
 * @param strCompany
 * @return use isEmpty() to check result
 */
QJsonObject BsLocalDataUserFind(const QString &strUser, const QString &strCompany){
    QJsonObject jEmpty;

    QString strPath = BS_LOCAL_DATA_FILE_NAME;
    QFile fileData;
    fileData.setFileName(strPath);
    //qDebug("%s--current path:%s",__FUNCTION__, qPrintable(QDir::currentPath()));
    //qDebug("%s--data path:%s",__FUNCTION__, qPrintable(strPath));
    bool canOpen = fileData.open(QIODevice::ReadWrite | QIODevice::Text);
    if(!canOpen){
        Logger::instance().addMessage("%s-BsLocalDataUserFind-failed to open file %s"+ strPath);
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return jEmpty;
    }

    QByteArray bufContent = fileData.readAll();
    fileData.close();
    if(bufContent.count() == 0){
        qDebug("%s--local data empty",__FUNCTION__);
        return jEmpty;
    }

    QString strContent = "";
    strContent = bufContent;
    strContent = strContent.trimmed();

    QJsonParseError jErr;
    QJsonDocument jDoc = QJsonDocument::fromJson(strContent.toUtf8(),&jErr) ;
    if(jErr.error != QJsonParseError::NoError || !jDoc.isObject()){
        qDebug("%s--failed to parse json :%s:%s",__FUNCTION__,qPrintable(jErr.errorString()),qPrintable(strContent));
        return jEmpty;
    }

    QJsonObject jObjRoot = jDoc.object();
    QJsonObject jObjUserTable = jObjRoot[BS_TABLE_USER].toObject();
    if(jObjUserTable.isEmpty()){
        qDebug("%s--failed to get usertable %s",__FUNCTION__,qPrintable(strContent));
        return jEmpty;
    }
    QString strKey = strCompany + BS_LOCAL_DATA_SPLITTER + strUser;
    QJsonObject jObjUserFound = jObjUserTable[strKey].toObject();
    if(jObjUserFound.isEmpty()){
        return jEmpty;
    }

    return jObjUserFound;
}


/**
 * @brief BsLocalDataUserList
 * list all user from local file data
 * @return use isEmpty() to check result
 */
QJsonObject BsLocalDataUserList(){
    QJsonObject jEmpty;

    QString strPath = BS_LOCAL_DATA_FILE_NAME;
    QFile fileData;
    fileData.setFileName(strPath);
    //qDebug("%s--current path:%s",__FUNCTION__, qPrintable(QDir::currentPath()));
    //qDebug("%s--data path:%s",__FUNCTION__, qPrintable(strPath));
    bool canOpen = fileData.open(QIODevice::ReadWrite | QIODevice::Text);
    if(!canOpen){
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return jEmpty;
    }

    QByteArray bufContent = fileData.readAll();
    fileData.close();
    if(bufContent.count() == 0){
        qDebug("%s--local data empty",__FUNCTION__);
        return jEmpty;
    }

    QString strContent = "";
    strContent = bufContent;
    strContent = strContent.trimmed();

    QJsonParseError jErr;
    QJsonDocument jDoc = QJsonDocument::fromJson(strContent.toUtf8(),&jErr) ;
    if(jErr.error != QJsonParseError::NoError || !jDoc.isObject()){
        qDebug("%s--failed to parse json :%s:%s",__FUNCTION__,qPrintable(jErr.errorString()),qPrintable(strContent));
        return jEmpty;
    }

    QJsonObject jObjRoot = jDoc.object();
    QJsonObject jObjUserTable = jObjRoot[BS_TABLE_USER].toObject();
    if(jObjUserTable.isEmpty()){
        qDebug("%s--failed to get usertable %s",__FUNCTION__,qPrintable(strContent));
        return jEmpty;
    }

    return jObjUserTable;
}

/**
 * @brief BsLocalDataUserUpdate,
 * update json data for a user
 * @param strUser
 * @param strCompany
 * @param jObjUser user json to write
 * @return err:<0,ok:>=0
 */
int BsLocalDataUserUpdate(const QJsonObject &jObjUser){
    QJsonObject jEmpty;

    if(jObjUser.isEmpty()){
        return -1;
    }

    QString strPath = BS_LOCAL_DATA_FILE_NAME;
    QFile fileData;
    fileData.setFileName(strPath);
    //qDebug("%s--current path:%s",__FUNCTION__, qPrintable(QDir::currentPath()));
    //qDebug("%s--data path:%s",__FUNCTION__, qPrintable(strPath));
    bool canOpen = fileData.open(QIODevice::ReadWrite | QIODevice::Text);
    if(!canOpen){
        Logger::instance().addMessage("%s-BsLocalDataUserUpdate-failed to open file %s"+ strPath);
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return -1;
    }

    QByteArray bufContent = fileData.readAll();
    fileData.close();
    if(bufContent.count() == 0){
        qDebug("%s--local data empty",__FUNCTION__);
        return -1;
    }

    QString strContent = "";
    strContent = bufContent;
    strContent = strContent.trimmed();

    QJsonParseError jErr;
    QJsonDocument jDoc = QJsonDocument::fromJson(strContent.toUtf8(),&jErr) ;
    if(jErr.error != QJsonParseError::NoError || !jDoc.isObject()){
        qDebug("%s--failed to parse json :%s:%s",__FUNCTION__,qPrintable(jErr.errorString()),qPrintable(strContent));
        return -1;
    }

    QJsonObject jObjRoot = jDoc.object();
    QJsonObject jObjUserTable = jObjRoot[BS_TABLE_USER].toObject();
    if(jObjUserTable.isEmpty()){
        qDebug("%s--failed to get usertable %s",__FUNCTION__,qPrintable(strContent));
        return -1;
    }

    QString strKey = jObjUser[BS_FIELD_USER_COMPANY].toString() + BS_LOCAL_DATA_SPLITTER + jObjUser[BS_FIELD_USER_NAME].toString();

    jObjUserTable[strKey] = jObjUser;
    jObjRoot[BS_TABLE_USER] = jObjUserTable;
    jDoc.setObject(jObjRoot);

    canOpen = fileData.open(QIODevice::WriteOnly |QIODevice::Truncate);
    if(!canOpen){
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return -1;
    }
    qint64 iResult = fileData.write( jDoc.toJson() );
    if(iResult < 0){
        qDebug("failed to write file");
    }
    fileData.close();

    return 1;
}

/**
 * @brief BsLocalDataUserDelete
 * @param strUser
 * @param strCompany
 * @return err:<0,ok:>=0
 */
int BsLocalDataUserDelete(const QString &strUser, const QString &strCompany){
    QJsonObject jEmpty;

    QString strPath = BS_LOCAL_DATA_FILE_NAME;
    QFile fileData;
    fileData.setFileName(strPath);
    //qDebug("%s--current path:%s",__FUNCTION__, qPrintable(QDir::currentPath()));
    //qDebug("%s--data path:%s",__FUNCTION__, qPrintable(strPath));
    bool canOpen = fileData.open(QIODevice::ReadWrite | QIODevice::Text);
    if(!canOpen){
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return -1;
    }

    QByteArray bufContent = fileData.readAll();
    fileData.close();
    if(bufContent.count() == 0){
        qDebug("%s--local data empty",__FUNCTION__);
        return -1;
    }

    QString strContent = "";
    strContent = bufContent;
    strContent = strContent.trimmed();

    QJsonParseError jErr;
    QJsonDocument jDoc = QJsonDocument::fromJson(strContent.toUtf8(),&jErr) ;
    if(jErr.error != QJsonParseError::NoError || !jDoc.isObject()){
        qDebug("%s--failed to parse json :%s:%s",__FUNCTION__,qPrintable(jErr.errorString()),qPrintable(strContent));
        return -1;
    }

    QJsonObject jObjRoot = jDoc.object();
    QJsonObject jObjUserTable = jObjRoot[BS_TABLE_USER].toObject();
    if(jObjUserTable.isEmpty()){
        qDebug("%s--failed to get usertable %s",__FUNCTION__,qPrintable(strContent));
        return -1;
    }

    QString strKey = strCompany + BS_LOCAL_DATA_SPLITTER + strUser;

    jObjUserTable.remove(strKey);

    jObjRoot[BS_TABLE_USER] = jObjUserTable;
    jDoc.setObject(jObjRoot);

    canOpen = fileData.open(QIODevice::WriteOnly |QIODevice::Truncate);
    if(!canOpen){
        qDebug("%s--failed to open file %s",__FUNCTION__,qPrintable(strPath));
        return -1;
    }
    qint64 iResult = fileData.write( jDoc.toJson() );
    if(iResult < 0){
        qDebug("failed to write file");
    }
    fileData.close();

    return 1;
}
#ifndef __h_BsUtil
#define __h_BsUtil

#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>

#define BS_LOCAL_DATA_FILE_NAME "data.json"
#define BS_LOCAL_DATA_SPLITTER "|"
#define BS_TABLE_USER "user_table"
#define BS_FIELD_USER_NAME "username"
#define BS_FIELD_USER_COMPANY "compname"
#define BS_FIELD_USER_TIME "time"

/**
 * @brief BsJsonObjToStr
 * @param jObj
 * @return empty string when the source object is empty
 */
QString BsJsonObjToStr(const QJsonObject &jObj );

/**
 * @brief BsLocalDataUserRead
 * find a user from local file data
 * @param strUser
 * @param strCompany
 * @return use isEmpty() to check result
 */
QJsonObject BsLocalDataUserFind(const QString &strUser, const QString &strCompany);

/**
 * @brief BsLocalDataUserList
 * list all user from local file data
 * @return use isEmpty() to check result
 */
QJsonObject BsLocalDataUserList();

/**
 * @brief BsLocalDataUserUpdate,
 * update json data for a user
 * @param jObjUser user json to update,will be inserted if not existed
 * @return err:<0,ok:>=0
 */
int BsLocalDataUserUpdate(const QJsonObject &jObjUser);

/**
 * @brief BsLocalDataUserDelete
 * @param strUser
 * @param strCompany
 * @return err:<0,ok:>=0
 */
int BsLocalDataUserDelete(const QString &strUser, const QString &strCompany);


#endif

调用,存储数据

QJsonObject jObjUser = BsLocalDataUserFind(username,compname);
qDebug("%s--objuser:%s",__FUNCTION__, qPrintable( BsJsonObjToStr(jObjUser)));
   if(jObjUser.isEmpty()){
       jObjUser["time"] = QDateTime::currentDateTime().toString();
       jObjUser["compname"] = compname;
       jObjUser["username"] = username;
       jObjUser["name"] = loginname;
       jObjUser["pwd"] = loginpwd;
       jObjUser["server"] = servername;
       int iResult = BsLocalDataUserUpdate(jObjUser);
       qDebug("%s--write result:%d",__FUNCTION__, iResult );
     }else{
       qDebug()<<"已存在";
     }

调用删除数据


 QString cmpname = companyids.at(position);
 QString username = usernames.at(position);
 BsLocalDataUserDelete(username,cmpname);

调用读取

    QJsonObject jObjList = BsLocalDataUserList();
    qDebug("%s--objList:%s",__FUNCTION__, qPrintable( BsJsonObjToStr(jObjList) ) );

    QStringList keyList = jObjList.keys();
    for(int i = 0; i < keyList.count(); i++){
        QString strKey = keyList.at(i);
        qDebug()<<"strKey="<<strKey;
        QJsonObject jObjTempUser = jObjList[strKey].toObject();
        QString compname = jObjTempUser["compname"].toString();
        QString username = jObjTempUser["username"].toString();
        QString vpnname = jObjTempUser["name"].toString();
        QString vpnpwd = jObjTempUser["pwd"].toString();
        QString vpnserver = jObjTempUser["server"].toString();
        if(!compname.isEmpty()){
            companyids.append(compname);
            usernames.append(username);
            vpnnames.append(vpnname);
            vpnpwds.append(vpnpwd);
            vpnservers.append(vpnserver);
        }
        //        qDebug("%s--compname:%s,username:%s,vpnname:%s,vpnpwd:%s,vpnserver:%s",__FUNCTION__, qPrintable(compname),qPrintable(username), qPrintable(vpnname),qPrintable(vpnpwd), qPrintable(vpnserver));
    }



版权声明:本文为dhd040805原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。