总体步骤:
1、先定义读写配置文件类。
2、类的初始化
3、读配置函数:
4、写入配置信息函数:
5、使用配置文件:
6、保存配置文件:
具体实现:
1、读写配置文件类:
class AppConfig
{
public:
static QString ConfigFile; //配置文件路径
//TCP客户端配置参数
static bool HexSendTcpClient; //16进制发送
static bool HexReceiveTcpClient; //16进制接收
static QString TcpServerIP; //服务器地址
static int TcpServerPort; //服务器端口
//读写配置参数
static void readConfig(); //读取配置参数
static void writeConfig(); //写入配置参数
};
2、类的初始化
QString AppConfig::ConfigFile = "config.ini";
bool AppConfig::HexSendTcpClient = false;
bool AppConfig::HexReceiveTcpClient = false;
QString AppConfig::TcpServerIP = "127.0.0.1";
int AppConfig::TcpServerPort = 6000;
3、读配置函数:
void AppConfig::readConfig()
{
QSettings set(AppConfig::ConfigFile, QSettings::IniFormat);
set.beginGroup("TcpClientConfig");
AppConfig::HexSendTcpClient = set.value("HexSendTcpClient", AppConfig::HexSendTcpClient).toBool();
AppConfig::HexReceiveTcpClient = set.value("HexReceiveTcpClient", AppConfig::HexReceiveTcpClient).toBool();
AppConfig::TcpServerIP = set.value("TcpServerIP", AppConfig::TcpServerIP).toString();
AppConfig::TcpServerPort = set.value("TcpServerPort", AppConfig::TcpServerPort).toInt();
set.endGroup();
//配置文件不存在或者不全则重新生成
if (!checkIniFile(AppConfig::ConfigFile)) {
writeConfig();
return;
}
}
4、写入配置信息:
void AppConfig::writeConfig()
{
QSettings set(AppConfig::ConfigFile, QSettings::IniFormat);
set.beginGroup("TcpClientConfig");
set.setValue("HexSendTcpClient", AppConfig::HexSendTcpClient);
set.setValue("HexReceiveTcpClient", AppConfig::HexReceiveTcpClient);
set.setValue("TcpServerIP", AppConfig::TcpServerIP);
set.setValue("TcpServerPort", AppConfig::TcpServerPort);
set.endGroup();
}
5、使用配置文件:
socket->connectToHost(AppConfig::TcpServerIP, AppConfig::TcpServerPort);
6、保存配置文件:
AppConfig::HexSendTcpClient = ui->ckHexSend->isChecked();
AppConfig::HexReceiveTcpClient = ui->ckHexReceive->isChecked();
AppConfig::TcpServerIP = ui->txtServerIP->text().trimmed();
AppConfig::TcpServerPort = ui->txtServerPort->text().trimmed().toInt();
AppConfig::writeConfig();