您的位置:首页 > 编程语言 > Qt开发

[Qt] QSettings(ini文件、注册表)[2013-08-13更新]

2013-08-13 08:26 381 查看
- ini文件读写

#include <QSettings>
...

QSettings *iniFile = new QSettings("conf.ini", QSettings::IniFormat, this);

// 解决中文读写问题(for Windows)

// 程序编码设置为“SYSTEM”

iniFile->setIniCodec("UTF-8");

or

iniFile->setIniCodec("GB2312");

----------------------------------------------------------------------

- 写入

// 在 [SEC_1] 中写入KEY_1、KEY_2的键值(如果 [SEC_1] 不存在则创建该节)

iniFile->beginGroup("SEC_1");

iniFile->setValue("KEY_1", "VALUE_1");

iniFile->setValue("KEY_2", "VALUE_2");

...

iniFile->endGroup();

// 在 [SEC_1] 中写入KEY_1、KEY_2的键值(如果 [SEC_1] 不存在则创建该节)

iniFile->setValue("SEC_1/KEY_1", "VALUE_1");

iniFile->setValue("SEC_1/KEY_2", "VALUE_2");

// 若不指定节,KEY_1会被保存在 [General] 中

iniFile->setValue("KEY_1", "VALUE_1");

// [General] 为保留节,用户无法指定

iniFile->setValue("General/KEY_1", "VALUE_1");
    上述代码输出的结果为:
    -------------------------------------------------

    [%General]       // 自动添加了“%”和系统保留的区分

    KEY_1=VALUE_1

    -------------------------------------------------

----------------------------------------------------------------------
    
- 读取

   

qDebug() << iniFile->allKeys();         // 返回所有键(格式:section/key)

qDebug() << iniFile->childGroups();     // 返回所有节

// 返回SEC_1节的所有键

// 若 childKeys() 在 beginGroup() 与 endGroup() 之外被调用将返回空值

iniFile->beginGroup("SEC_1");

qDebug() << iniFile->childKeys();

iniFile->endGroup();

iniFile->beginGroup("SEC_1");

qDebug() << iniFile->value("KEY_1");        // 返回 [SEC_1] 中KEY_1键的值

iniFile->endGroup();

qDebug() << iniFile->value("SEC_1/KEY_1");  // 返回 [SEC_1] 中KEY_1键的值

delete iniFile;

- 注册表读写

QString regKey = "SOFTWARE/Microsoft/Windows/CurrentVersion/Run/Your_Program";
QString sApp = QCoreApplication::applicationFilePath();
QString linkPath = sApp;
linkPath = linkPath.replace("exe", "lnk");
QFile::link(sApp, linkPath);
linkPath.replace("/", "\\");
QSettings *reg = new QSettings("HKEY_LOCAL_MACHINE", QSettings::NativeFormat);

if (reg->value(regKey).toString() != linkPath)
{
    qDebug() << "Update regedit...";
    reg->setValue(regKey, QVariant(linkPath));
}

- 开机自动运行(在MainWindow构造函数中执行)

QString sApp = QCoreApplication::applicationFilePath();

sApp.replace("/", "\\");

QSettings *reg = new QSettings("HKEY_LOCAL_MACHINE", QSettings::NativeFormat);

reg->setValue("SOFTWARE/Microsoft/Windows/CurrentVersion/Run/Your_Program", QVariant(sApp));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: