QDebugStateSaver Class

Convenience class for custom QDebug operators. More...

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

Public Functions

Detailed Description

Saves the settings used by QDebug, and restores them upon destruction, then calls maybeSpace(), to separate arguments with a space if autoInsertSpaces() was true at the time of constructing the QDebugStateSaver.

The automatic insertion of spaces between writes is one of the settings that QDebugStateSaver stores for the duration of the current block.

The settings of the internal QTextStream are also saved and restored, so that using << Qt::hex in a QDebug operator doesn't affect other QDebug operators.

QDebugStateSaver is typically used in the implementation of an operator<<() for debugging:

QDebug operator<<(QDebug dbg, const Message &message)
{
    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;
}

Member Function Documentation

QDebugStateSaver::QDebugStateSaver(QDebug &dbg)

Creates a QDebugStateSaver instance, which saves the settings currently used by dbg.

See also QDebug::setAutoInsertSpaces() and QDebug::autoInsertSpaces().

[noexcept] QDebugStateSaver::~QDebugStateSaver()

Destroys a QDebugStateSaver instance, which restores the settings used when the QDebugStateSaver instance was created.

See also QDebug::setAutoInsertSpaces() and QDebug::autoInsertSpaces().

© 2024 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.