Qt读取ini配置文件
ini文件保存数据库参数,密码使用Base64加密。
生成的config.ini内容如下:
[database] ip=127.0.0.1 port=3306 user=root passwd=d2p5MTIz [notice] version=v1.0 time=2021-03-03 18:23:47
程序Demo如下
mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 #include <QSettings> 6 #include <QtDebug> 7 #include <QDateTime> 8 9 QT_BEGIN_NAMESPACE 10 namespace Ui { class MainWindow; } 11 QT_END_NAMESPACE 12 13 class MainWindow : public QMainWindow 14 { 15 Q_OBJECT 16 17 public: 18 MainWindow(QWidget *parent = nullptr); 19 ~MainWindow(); 20 21 void write_congig_ini(QString ip,QString port,QString user,QString passwd); 22 void read_config_ini(QString &ip,QString &port,QString &user,QString &passwd); 23 24 25 private slots: 26 void on_pushButton_clicked(); 27 void on_pushButton_2_clicked(); 28 29 private: 30 Ui::MainWindow *ui; 31 32 QString ip; 33 QString port; 34 QString user; 35 QString passwd; 36 37 }; 38 #endif // MAINWINDOW_H
mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 } 10 11 MainWindow::~MainWindow() 12 { 13 delete ui; 14 } 15 16 void MainWindow::write_congig_ini(QString ip,QString port,QString user,QString passwd){ 17 18 QSettings *config = new QSettings("config.ini",QSettings::IniFormat); 19 20 config->setValue("/database/ip",ip); 21 config->setValue("/database/port",port); 22 config->setValue("/database/user",user); 23 config->setValue("/database/passwd",QString::fromUtf8(passwd.toUtf8().toBase64())); 24 25 config->setValue("/notice/version","v1.0"); 26 config->setValue("/notice/time",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); 27 28 config->deleteLater(); 29 } 30 31 void MainWindow::read_config_ini(QString &ip,QString &port,QString &user,QString &passwd){ 32 33 QSettings *config = new QSettings("config.ini",QSettings::IniFormat); 34 35 ip = config->value("/database/ip").toString(); 36 port = config->value("/database/port").toString(); 37 user = config->value("/database/user").toString(); 38 passwd = QByteArray::fromBase64(config->value("/database/passwd").toString().toUtf8()); 39 40 QString version = config->value("/notice/version").toString(); 41 QString time = config->value("/notice/time").toString(); 42 43 config->deleteLater(); 44 45 } 46 47 void MainWindow::on_pushButton_clicked() 48 { 49 write_congig_ini("127.0.0.1","3306","root","wjy123"); 50 51 } 52 53 void MainWindow::on_pushButton_2_clicked() 54 { 55 read_config_ini(ip,port,user,passwd); 56 }