本页内容

QDebugStateSaver Class

用于自定义QDebug 运算符的便捷类。更多内容...

标题: #include <QDebugStateSaver>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

公共函数

详细说明

保存QDebug 使用的设置,并在销毁时恢复这些设置,随后调用maybeSpace(),若在构造QDebugStateSaver时autoInsertSpaces()的值为true,则用空格分隔参数。

在写入之间自动插入空格是 QDebugStateSaver 在当前代码块期间保存的设置之一。

内部的QTextStream 的设置也会被保存和恢复,因此,在QDebug 运算符中使用 <<Qt::hex 不会影响其他QDebug 运算符。

QDebugStateSaver 通常用于实现用于调试的 << 操作符:

QDebug operator<<(QDebug dbg, const Message &message)
{
    QDebugStateSaver saver(dbg);
    const QList<QStringView> pieces = message.body().split(u"\r\n", Qt::SkipEmptyParts);
    if (pieces.isEmpty())
        dbg.nospace() << "Message()";
    else if (pieces.size() == 1)
        dbg.nospace() << "Message(" << pieces.first() << ")";
    else
        dbg.nospace() << "Message(" << pieces.first() << " ...)";
    return dbg;
}

成员函数文档

QDebugStateSaver::QDebugStateSaver(QDebug &dbg)

创建一个 QDebugStateSaver 实例,用于保存dbg 当前使用的设置。

另请参阅 QDebug::setAutoInsertSpaces() 和QDebug::autoInsertSpaces()。

[noexcept] QDebugStateSaver::~QDebugStateSaver()

销毁一个QDebugStateSaver 实例,这将恢复QDebugStateSaver 实例创建时使用的设置。

另请参阅 QDebug::setAutoInsertSpaces() 和QDebug::autoInsertSpaces()。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.