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

如何让Qt的QFont::fromString函数不向控制台输出日志?

如何抑制QFont::fromString的无效输入日志输出?

我的代码实现如下:

QString input = in.readLine();
if (!s.computers_font.fromString(input)){
    s.computers_font = backup.computers_font;
}

当输入字符串损坏或为空时,程序会正常使用备份字体(fromString返回的布尔值表示调用是否成功),但此时控制台会输出日志:

QFont::fromString: Invalid description '(empty)'

请问如何抑制该日志输出行为?


解决方法

1. 提前校验输入字符串

在调用fromString之前先检查输入合法性,从根源避免触发错误日志:

QString input = in.readLine();
// 过滤空字符串或空白字符组成的无效输入
if (input.trimmed().isEmpty()) {
    s.computers_font = backup.computers_font;
} else {
    if (!s.computers_font.fromString(input)) {
        s.computers_font = backup.computers_font;
    }
}

2. 临时调整Qt消息输出等级

如果无法提前校验,可临时禁用警告类消息,执行完目标代码后恢复原配置:

QString input = in.readLine();
// 保存原消息处理函数
QtMsgHandler originalHandler = qInstallMessageHandler(nullptr);
// 临时忽略警告及以下等级的消息
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& context, const QString& msg) {
    if (type > QtWarningMsg) { // 仅保留错误及以上等级的日志输出
        originalHandler(type, context, msg);
    }
});

// 执行字体解析逻辑
if (!s.computers_font.fromString(input)){
    s.computers_font = backup.computers_font;
}

// 恢复原消息处理逻辑
qInstallMessageHandler(originalHandler);

3. 全局过滤特定日志消息

若需长期忽略这类日志,可在程序初始化时设置全局消息过滤器:

// 示例:在main函数开头添加
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& context, const QString& msg) {
    // 跳过QFont::fromString的无效描述警告
    if (type == QtWarningMsg && msg.startsWith("QFont::fromString: Invalid description")) {
        return;
    }
    // 其他消息按默认格式输出
    QByteArray localMsg = msg.toLocal8Bit();
    fprintf(stderr, "%s: %s (%s:%u, %s)\n",
            qPrintable(Qt::msgTypeToString(type)),
            localMsg.constData(),
            context.file, context.line,
            context.function);
});

内容的提问来源于stack exchange,提问作者Isaac D. Cohen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:07:11