You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在QSettings中保存不带引号的QString至.ini文件?

解决QSettings保存QString到INI文件自动加引号的问题

以下是两种无需读取时截取引号的实现方法:

方法一:手动直接写入INI文件

直接通过文件操作类控制写入内容,完全避免QSettings自动添加引号的逻辑,适合简单场景:

QString s = "xwr289vjkloji9";
QFile file("file.ini");
// 若要覆盖原有内容,将Append替换为Truncate
if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
    QTextStream out(&file);
    out << "dbp=" << s << "\n";
    file.close();
}

如果需要修改已有INI文件的指定键,需先读取全部内容、修改对应项后再重新写入。

方法二:自定义QSettings的INI格式

注册自定义的INI格式处理函数,既保留QSettings的分组、多键管理等功能,又能控制字符串写入时的格式:

// 自定义INI写入逻辑:字符串直接输出,不加引号
bool writeCustomIni(QIODevice &device, const QSettings::SettingsMap &map) {
    QTextStream out(&device);
    for (const auto &key : map.keys()) {
        const QVariant &value = map[key];
        if (value.type() == QVariant::String) {
            out << key << "=" << value.toString() << "\n";
        } else {
            // 非字符串类型按默认逻辑处理
            out << key << "=" << value.toString() << "\n";
        }
    }
    return true;
}

// 自定义INI读取逻辑:直接读取无引号的字符串
bool readCustomIni(QIODevice &device, QSettings::SettingsMap &map) {
    QTextStream in(&device);
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty() || line.startsWith(';')) continue;
        int eqIndex = line.indexOf('=');
        if (eqIndex == -1) continue;
        
        QString key = line.left(eqIndex).trimmed();
        QString value = line.mid(eqIndex + 1).trimmed();
        map[key] = value;
    }
    return true;
}

// 注册自定义INI格式
int customIniFormat = QSettings::registerFormat("ini", readCustomIni, writeCustomIni);

// 使用自定义格式保存字符串
QString s = "xwr289vjkloji9";
QSettings settings("file.ini", customIniFormat);
settings.setValue("dbp", s);

注:QSettings默认给字符串加引号是遵循INI文件规范,当字符串包含空格、特殊字符时引号是必要的防护措施,以上方法仅适合纯无特殊字符的字符串场景。

内容的提问来源于stack exchange,提问作者Me3nTaL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:25:17