c++客户端开发——软件关闭后的窗口设置的保存(配置文件读取与保存)

系列文章目录


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

`在C++程序设计中,实现软件当前设置在下次启动时保持的功能通常涉及到数据的持久化存储,利用开源库json可以非常方便的实现该功能。


一、实现工具

1、JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于语言的文本格式来存储和表示数据。简单、清晰且易于阅读和编写,同时也易于机器解析和生成。因其简洁、易于阅读和解析的特性,在 Web 服务、配置文件、数据交换等领域得到了广泛的应用。本文中主要关注其实现配置文件写入和读取。

2、QSettings 是 Qt 框架中用于存储和检索应用程序设置的一个类,一般在Qt开发中使用。它提供了一种跨平台的方式来保存和恢复应用程序的配置信息,如窗口大小、位置、用户首选项等。QSettings 类可以处理多种存储格式,包括 INI 文件、Windows 系统注册表(在 Windows 上)、XML 文件等,具体取决于你使用的平台和指定的格式。

二、基于nlohmann/json开源库开发

2.1.库下载

为现代c++设计的开源json库

2.2.库目录结构

json库根目录所需要的头文件在single_include/nlohmann目录下

2.3.文心一言示例

//保存设置到json文件
#include "nlohmann/json.hpp"  
#include <fstream>  
  
void saveSettings(const nlohmann::json& settings, const std::string& filename) {  
    std::ofstream o(filename);  
    o << std::setw(4) << settings << std::endl;  
}  
  
// 使用示例  
nlohmann::json settings;  
settings["volume"] = 50;  
settings["theme"] = "dark";  
saveSettings(settings, "settings.json");
//从json文件读取设置
#include "nlohmann/json.hpp"  
#include <fstream>  
#include <iostream>  
  
nlohmann::json loadSettings(const std::string& filename) {  
    std::ifstream i(filename);  
    nlohmann::json j;  
    i >> j;  
    return j;  
}  
  
// 使用示例  
nlohmann::json settings = loadSettings("settings.json");  
int volume = settings["volume"];  
std::string theme = settings["theme"];  
std::cout << "Volume: " << volume << ", Theme: " << theme << std::endl;

2.4.窗口类集成json配置文件

//.h文件
#include <QMainWindow>
#include <QSlider>
#include <QCheckBox>
#include <QSpinBox>
#include <QHBoxLayout>
#include "json.hpp"
#include <fstream>
#include <memory>

void qwsaveSettings(const nlohmann::json& settings, const std::string& filename);
nlohmann::json qwloadSettings(const std::string& filename);

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(const std::string& setFile);  //构造对象时提供实参:“配置文件名”,如:MainWindow window1("window1_settingfile.json")
    ~MainWindow();

private:
    const std::string setFileName;
//以下为窗口上组件的指针
    std::unique_ptr<QWidget> centralWidget;
    std::unique_ptr<QSlider> sliderptr;
    std::unique_ptr<QCheckBox> checkBoxptr;
    std::unique_ptr<QSpinBox> spinBoxptr;
    std::unique_ptr<QHBoxLayout> layoutptr;
};
#include "mainwindow.h"

void qwsaveSettings(const nlohmann::json& settings, const std::string& filename){
    std::ofstream o(filename);
    o << std::setw(4) << settings << std::endl;
}

nlohmann::json qwloadSettings(const std::string& filename){
    std::ifstream i(filename);
    nlohmann::json j;
    if(i.good())
        i >> j;
    return j;
}
//在构造函数中读取.json文件,若文件不存在则使用初始设置
MainWindow::MainWindow(const std::string& setFile)
    : setFileName{setFile}
    ,centralWidget{new QWidget()}
    ,sliderptr{new QSlider(Qt::Horizontal)}
    ,checkBoxptr{new QCheckBox()}
    ,spinBoxptr{new QSpinBox()}
    ,layoutptr{new QHBoxLayout()}
{
    nlohmann::json settings=qwloadSettings(setFileName);
    sliderptr->setMaximum(10);
    sliderptr->setMinimum(0);
    checkBoxptr->setText("开关");
    spinBoxptr->setMaximum(10);
    spinBoxptr->setMinimum(0);
    if(settings.empty()){	//判断配置文件是否为空,文件不存在也为空	
        sliderptr->setValue(0);
        spinBoxptr->setValue(0);
    }
    else{
        sliderptr->setValue(settings["sliderval"]);
        auto b=settings["checkBval"].get<bool>();
        checkBoxptr->setChecked(b);
        spinBoxptr->setValue(settings["spinBval"]);
    }
    layoutptr->addWidget(sliderptr.get());
    layoutptr->addWidget(checkBoxptr.get());
    layoutptr->addWidget(spinBoxptr.get());
    this->setCentralWidget(centralWidget.get());
    centralWidget->setLayout(layoutptr.get());
}

MainWindow::~MainWindow()
{
    nlohmann::json settings;
    settings["sliderval"] = sliderptr->value();
    settings["checkBval"] = (checkBoxptr->isChecked());
    settings["spinBval"] = spinBoxptr->value();
    qwsaveSettings(settings, setFileName);
}

MainWindow::~MainWindow()
{//析构函数时对配置文件进行写入,提示:由于本例中类内控件指针声明为智能指针,它们会自动释放
    nlohmann::json settings;
    settings["sliderval"] = sliderptr->value();
    settings["checkBval"] = (int)(checkBoxptr->isChecked()); //nlohmann::json读取Bool类型会有异常抛出
    settings["spinBval"] = spinBoxptr->value();
    qwsaveSettings(settings, setFileName);
}

三、Qt 基于QSetting库开发

#include <QMainWindow>
#include <QSettings>     //包含QSetting头文件
#include <QSlider>
#include <QCheckBox>
#include <QSpinBox>
#include <QHBoxLayout>

QT_BEGIN_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(const QString& setFile);
    ~MainWindow();

private:
    const QString setFileName;
    std::unique_ptr<QWidget> centralWidget;
    std::unique_ptr<QSlider> sliderptr;
    std::unique_ptr<QCheckBox> checkBoxptr;
    std::unique_ptr<QSpinBox> spinBoxptr;
    std::unique_ptr<QHBoxLayout> layoutptr;
};
#include "mainwindow.h"


MainWindow::MainWindow(const QString& setFile)
    : setFileName{setFile}
    ,centralWidget{new QWidget()}
    ,sliderptr{new QSlider(Qt::Horizontal)}
    ,checkBoxptr{new QCheckBox()}
    ,spinBoxptr{new QSpinBox()}
    ,layoutptr{new QHBoxLayout()}
{
    QSettings settings(setFileName,QSettings::IniFormat);
    sliderptr->setMaximum(10);
    sliderptr->setMinimum(0);
    checkBoxptr->setText("开关");
    spinBoxptr->setMaximum(10);
    spinBoxptr->setMinimum(0);
//QSetting对象判断是否为空需要借助QStringList的allKeys()方法
    QStringList keys=settings.allKeys();
    if(keys.isEmpty()){
        sliderptr->setValue(0);
        spinBoxptr->setValue(0);
    }
    else{
        sliderptr->setValue(settings.value("sliderval").toInt());
        checkBoxptr->setChecked(settings.value("checkBval").toBool());
        spinBoxptr->setValue(settings.value("spinBval").toInt());
    }
    layoutptr->addWidget(sliderptr.get());
    layoutptr->addWidget(checkBoxptr.get());
    layoutptr->addWidget(spinBoxptr.get());
    this->setCentralWidget(centralWidget.get());
    centralWidget->setLayout(layoutptr.get());
}

MainWindow::~MainWindow()
{
    QSettings settings(setFileName,QSettings::IniFormat);
    settings.setValue("sliderval",sliderptr->value());
    settings.setValue("checkBval",checkBoxptr->isChecked());
    settings.setValue("spinBval",spinBoxptr->value());
}

四、demo效果演示

//main文件
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w("setting.ini");  //自定义MainWindows类初始化时以配置文件名作为实参。
    w.show();
    return a.exec();
}

QSetting配置保存读取demo

总结

nlohmann::json 是一个高效且易于使用的 C++ JSON 库,它允许开发者轻松地将 C++ 数据结构序列化为 JSON 格式,或者将 JSON 数据解析为 C++ 对象。在软件开发中,特别是在需要持久化或传输数据的场景下,nlohmann::json 提供了极大的便利。
Qt Settings 是 Qt 框架提供的一个用于存储和检索应用程序设置的机制。它允许开发者将应用程序的设置信息(如窗口大小、位置、用户偏好等)保存在跨平台的配置文件中,并在需要时轻松地检索这些设置。
它们都可以实现软件中的配置进行保存与读取,保证软件启动后各项配置载入最近一次使用时的状态,易于学习与使用,是桌面端开发的必要工具。


  • 18
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZW_finder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值