Qt debug information files что это

Qt Documentation

Contents

The QDebug class provides an output stream for debugging information. More.

Public Types

Public Functions

QDebug(const QDebug &o)
QDebug(QtMsgType t)
QDebug(QString *string)
QDebug(QIODevice *device)
QDebug &operator=(const QDebug &other)

QDebug()

boolautoInsertSpaces() const
QDebug &maybeQuote(char c = ‘»‘)
QDebug &maybeSpace()
QDebug &noquote()
QDebug &nospace()
QDebug &quote()
QDebug &resetFormat()
voidsetAutoInsertSpaces(bool b)
voidsetVerbosity(int verbosityLevel)
QDebug &space()
voidswap(QDebug &other)
QDebug &verbosity(int verbosityLevel)
intverbosity() const
QDebug &operator &flags)
QDebugoperator &list)
QDebugoperator &vec)
QDebugoperator &vec)
QDebugoperator &vec)
QDebugoperator &map)
QDebugoperator &map)
QDebugoperator &map)
QDebugoperator &hash)
QDebugoperator &pair)
QDebugoperator &set)

Detailed Description

QDebug is used whenever the developer needs to write out debugging or tracing information to a device, file, string or console.

Basic Use

In the common case, it is useful to call the qDebug() function to obtain a default QDebug object to use for writing debugging information.

This constructs a QDebug object using the constructor that accepts a QtMsgType value of QtDebugMsg. Similarly, the qWarning(), qCritical() and qFatal() functions also return QDebug objects for the corresponding message types.

The class also provides several constructors for other situations, including a constructor that accepts a QFile or any other QIODevice subclass that is used to write debugging information to files and other devices. The constructor that accepts a QString is used to write to a string for display or serialization.

Formatting Options

QDebug formats output so that it’s easily readable. It automatically adds spaces between arguments, and adds quotes around QString, QByteArray, QChar arguments.

You can tweak these options through the space(), nospace() and quote(), noquote() methods. Furthermore, QTextStream manipulators can be piped into a QDebug stream.

QDebugStateSaver limits changes to the formatting to the current scope. resetFormat() resets the options to the default ones.

Writing Custom Types to a Stream

Many standard types can be written to QDebug objects, and Qt provides support for most Qt value types. To add support for custom types, you need to implement a streaming operator, as in the following example:

This is described in the Debugging Techniques and Creating Custom Qt Types documents.

Member Type Documentation

enum QDebug:: VerbosityLevel

This enum describes the range of verbosity levels.

ConstantValue
QDebug::MinimumVerbosity0
QDebug::DefaultVerbosity2
QDebug::MaximumVerbosity7

This enum was introduced or modified in Qt 5.13.

Member Function Documentation

QDebug:: QDebug (const QDebug &o)

Constructs a copy of the other debug stream o.

QDebug:: QDebug ( QtMsgType t)

Constructs a debug stream that writes to the handler for the message type t.

QDebug:: QDebug ( QString *string)

Constructs a debug stream that writes to the given string.

QDebug:: QDebug ( QIODevice *device)

Constructs a debug stream that writes to the given device.

QDebug &QDebug:: operator= (const QDebug &other)

Assigns the other debug stream to this stream and returns a reference to this stream.

QDebug::

Flushes any pending data to be written and destroys the debug stream.

bool QDebug:: autoInsertSpaces () const

Returns true if this QDebug instance will automatically insert spaces between writes.

This function was introduced in Qt 5.0.

QDebug &QDebug:: maybeQuote ( char c = ‘»‘)

Writes a character c to the debug stream, depending on the current setting for automatic insertion of quotes, and returns a reference to the stream.

This function was introduced in Qt 5.4.

QDebug &QDebug:: maybeSpace ()

Writes a space character to the debug stream, depending on the current setting for automatic insertion of spaces, and returns a reference to the stream.

QDebug &QDebug:: noquote ()

Disables automatic insertion of quotation characters around QChar, QString and QByteArray contents and returns a reference to the stream.

When quoting is disabled, these types are printed without quotation characters and without escaping of non-printable characters.

This function was introduced in Qt 5.4.

QDebug &QDebug:: nospace ()

Disables automatic insertion of spaces and returns a reference to the stream.

QDebug &QDebug:: quote ()

Enables automatic insertion of quotation characters around QChar, QString and QByteArray contents and returns a reference to the stream.

Quoting is enabled by default.

This function was introduced in Qt 5.4.

QDebug &QDebug:: resetFormat ()

Resets the stream formatting options, bringing it back to its original constructed state.

This function was introduced in Qt 5.4.

void QDebug:: setAutoInsertSpaces ( bool b)

Enables automatic insertion of spaces between writes if b is true; otherwise automatic insertion of spaces is disabled.

This function was introduced in Qt 5.0.

void QDebug:: setVerbosity ( int verbosityLevel)

Sets the verbosity of the stream to verbosityLevel.

The allowed range is from 0 to 7. The default value is 2.

This function was introduced in Qt 5.6.

QDebug &QDebug:: space ()

Writes a space character to the debug stream and returns a reference to the stream.

The stream remembers that automatic insertion of spaces is enabled for future writes.

void QDebug:: swap ( QDebug &other)

Swaps this debug stream instance with other. This function is very fast and never fails.

This function was introduced in Qt 5.0.

QDebug &QDebug:: verbosity ( int verbosityLevel)

Sets the verbosity of the stream to verbosityLevel and returns a reference to the stream.

The allowed range is from 0 to 7. The default value is 2.

This function was introduced in Qt 5.13.

int QDebug:: verbosity () const

Returns the verbosity of the debug stream.

Streaming operators can check the value to decide whether verbose output is desired and print more information depending on the level. Higher values indicate that more information is desired.

The allowed range is from 0 to 7. The default value is 2.

This function was introduced in Qt 5.6.

QDebug &QDebug:: operator ( QChar t)

QDebug &QDebug:: operator ( bool t)

Writes the boolean value, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( char t)

Writes the character, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( short t)

Writes the signed short integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( unsigned short t)

Writes then unsigned short integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( char16_t t)

Writes the UTF-16 character, t, to the stream and returns a reference to the stream.

This function was introduced in Qt 5.5.

QDebug &QDebug:: operator ( char32_t t)

Writes the UTF-32 character, t, to the stream and returns a reference to the stream.

This function was introduced in Qt 5.5.

QDebug &QDebug:: operator ( int t)

Writes the signed integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( unsigned int t)

Writes then unsigned integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( long t)

Writes the signed long integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( unsigned long t)

Writes then unsigned long integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( qint64 t)

Writes the signed 64-bit integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( quint64 t)

Writes then unsigned 64-bit integer, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( float t)

Writes the 32-bit floating point number, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator ( double t)

Writes the 64-bit floating point number, t, to the stream and returns a reference to the stream.

QDebug &QDebug:: operator (const char *t)

Writes the ‘\0’-terminated string, t, to the stream and returns a reference to the stream. The string is never quoted nor transformed to the output, but note that some QDebug backends might not be 8-bit clean.

QDebug &QDebug:: operator (const QString &t)

Writes the string, t, to the stream and returns a reference to the stream. Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

QDebug &QDebug:: operator (const QStringRef &t)

Writes the string, t, to the stream and returns a reference to the stream. Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

See the QString overload for examples.

QDebug &QDebug:: operator ( QStringView s)

Writes the string view, s, to the stream and returns a reference to the stream. Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

See the QString overload for examples.

This function was introduced in Qt 5.10.

QDebug &QDebug:: operator ( QLatin1String t)

Writes the string, t, to the stream and returns a reference to the stream. Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

See the QString overload for examples.

QDebug &QDebug:: operator (const QByteArray &t)

Writes the byte array, t, to the stream and returns a reference to the stream. Normally, QDebug prints the array inside quotes and transforms control or non-US-ASCII characters to their C escape sequences (\xAB). This way, the output is always 7-bit clean and the string can be copied from the output and pasted back into C++ sources, if necessary.

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

Note how QDebug needed to close and reopen the string in the way C and C++ languages concatenate string literals so that the letter ‘b’ is not interpreted as part of the previous hexadecimal escape sequence.

QDebug &QDebug:: operator (const void *t)

Writes a pointer, t, to the stream and returns a reference to the stream.

Related Non-Members

template QDebug operator ( QDebug debug, const QFlags T > &flags)

Writes flags to debug.

This function was introduced in Qt 4.7.

template QDebug operator ( QDebug debug, const QList T > &list)

Writes the contents of list to debug. T needs to support streaming into QDebug.

template QDebug operator ( QDebug debug, const QVector T > &vec)

Writes the contents of vector vec to debug. T needs to support streaming into QDebug.

Writes the contents of vector vec to debug. T needs to support streaming into QDebug.

This function was introduced in Qt 5.7.

Writes the contents of list vec to debug. T needs to support streaming into QDebug.

This function was introduced in Qt 5.7.

Writes the contents of map to debug. Both Key and T need to support streaming into QDebug.

This function was introduced in Qt 5.7.

Writes the contents of map to debug. Both Key and T need to support streaming into QDebug.

This function was introduced in Qt 5.7.

Writes the contents of map to debug. Both Key and T need to support streaming into QDebug.

Writes the contents of hash to debug. Both Key and T need to support streaming into QDebug.

Writes the contents of pair to debug. Both T1 and T2 need to support streaming into QDebug.

template QDebug operator ( QDebug debug, const QSet T > &set)

Writes the contents of set to debug. T needs to support streaming into QDebug.

В© 2021 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.

Источник

Отладка с помощью Qt Creator

Введение

Qt Creator не имеет собственного отладчика. Вместо этого он предоставляет графический интерфейс к различным отладчикам:

ПлатформаКомпиляторОтладчик
Linux, Unixes, Mac OSgccGNU Symbolic Debugger (gdb)
Windows/MinGWgccGNU Symbolic Debugger (gdb)
WindowsMicrosoft Visual C++ CompilerDebugging Tools for Windows/Microsoft Console Debugger (CDB)

Интерфейс позволит вам отлаживать программу построчно и или по каждой инструкции, прерывать запущенную программу, устанавливать точки останова, просматривать содержимое стека вызовов, локальных и глобальных переменных и т. д.

В Qt Creator сырая информация, предоставляемая отладчиком, отображается явным и лаконичным образом, упрощая процесс отладки.

В дополнение к базовой функциональности IDE: просмотр стека, просмотр локальных и наблюдаемых переменных, регистров и т.д., Qt Creator имеет дополнительные особенности, делая отладку приложений, основанных на Qt, проще. Интерфейс отладчика знает о внутреннем устройстве некоторых классов Qt, таких как QString, контейнеры QTL и, что особенно важно, QObject (и унаследованные от него классы). Таким образом, он может ясно представлять данные Qt.

Замечания по установке отладчика

ОтладчикЗамечания
GdbТребует gdb версии 6.8.
Debugging Tools for WindowsИспользование этого отладчика требует установку пакета Debugging Tools for Windows 32-bit или 64-bit (версии 6.10 для 32-bit или 64-bit версии Qt Creator соответственно), который доступен для свободного скачивания с Microsoft Developer Network.

Собранная версия Qt SDK for Windows будет использовать библиотеку если она присутствует в системе. При сборке Qt Creator с использованием компилятора Microsoft Visual C++, будет проверен путь "%ProgramFiles%\Debugging Tools for Windows" чтобы убедиться что все необходимые заголовочные файлы присутствуют.

Взаимодействие с отладчиком

В режиме Отладка несколько прикрепляемых виджетов используется для взаимодействия с отлаживаемой программой. Часто используемые виджеты отображаются по умолчанию; используемые редко спрятаны. Для изменения настроек по умолчанию, выберите Отладка, а затем выберите Виды.

Qt debug information files что это. Смотреть фото Qt debug information files что это. Смотреть картинку Qt debug information files что это. Картинка про Qt debug information files что это. Фото Qt debug information files что это

Здесь вы можете заблокировать и разблокировать положение ваших видов, а также показать или спрятать их. Среди видов, которые вы можете отобразить есть Точки останова, Дизассемблер, Модули, Регистры, Отладчик, Стек и Поток. Расположение ваших прикрепляемых виджетов будет сохранено для последующих сессий.

Точки остановки

Точки останова показываются в виде Точки останова, который включён по умолчанию. Этот вид также доступен когда отладчик и отлаживаемая программа не запущены.

Точки останова представляют место или набор мест в коде, которые при выполнении прервут отлаживаемую программу и передадут управление пользователю. Пользователь может просмотреть состояние прерванной программы или продолжить выполнение построчно или непрерывно.

Также прерывание программы на точке останова может быть запрещено при определённых условиях.

Вы можете установить точки останова:

Вы можете удалить точку останова:

Точки останова могут быть установлены и удалены перед тем как программа будет запущена или во время её работы под отладчиком. Также точки останова могут быть сохранены вместе с сессией.

Выполнение

Чтобы запустить программу под отладчиком выберите в меню Отладка пункт Начать отладку, или просто нажмите F5. Qt Creator проверит является ли собранная программа актуальной и пересоберёт её при необходимости. Отладчик получит контроль и запустит программу.

Замечание: Запуск программы в отладчике может занять заметное количество времени, обычно в диапазоне от нескольких секунд до нескольких минут, если используются сложные особенности (как QtWebKit).

После запуска программы она работает как обычно; тоже самое и с производительностью. Пользователь может прервать выполняемую программу выбрав Прервать из меню Отладка. Программа автоматически прерывается как только дойдет до точки останова.

Как только программа остановиться, Qt Creator:

Вы можете использовать виды отладчика для более подробного просмотра данных.

Чтобы закончить отладку нажмите Shift+F5. Строка кода может быть исполнена как одно целое с F10; чтобы выполнить функцию или подфункцию используйте F11. Также вы можете продолжить выполнение программы с помощью F5. Можно продолжить выполнение программы до окончания текущей функции или перепрыгнуть на произвольную позицию в текущей функции.

Когда отлаживаемая программа прерывается, Qt Creator отображает наследованные вызовы процедур, приводящие к текущему положению в следе стека вызовов. След стека строится из кадров стека вызовов, каждый из которых представляет конкретную функцию. Для каждой функции Qt Creator попытается получить имя файла и номер строки соответствующих файлов исходных кодов. Эти данные отображаются в виде Стек.

Qt debug information files что это. Смотреть фото Qt debug information files что это. Смотреть картинку Qt debug information files что это. Картинка про Qt debug information files что это. Фото Qt debug information files что это

Так как стек вызовов, приводящий к текущему положению, может происходить из или проходить через код для которого нет отладочной информации, не все кадры стека могут иметь соответствующие положения в исходном коде. Эти кадры будут иметь серый цвет в виде Стек view.

Если вы щёлкните на кадре с известным положением в исходном коде, текстовый редактор перейдёт в соответствующее положение и обновит вид Локальные и наблюдаемые переменные, делая их видимыми как будто программа была прервана перед входом в функцию.

Потоки

Если прервано многопоточное приложение, то можно использовать вид Поток или выпадающий список с именем Поток в строке состояния отладчика для переключения от одного потока к другому. Вид Стек будет настраивать себя соответственно.

Локальные и наблюдаемые переменные

Когда бы программа не остановилась под контролем отладчика, он получает информацию о верхнем кадре стека и отображает его в виде Локальные и наблюдаемые переменные. Он обычно включает информацию о параметрах функции в этом кадре, а также локальные переменные.

Составные переменные структур или классов в виде будут отображены как «раскрываемые». Щёлкните на «+» чтобы раскрыть элемент и показать все его члены. Помимо отображаемые значения и типа, пользователь может просмотреть и перейти к низкоуровневой компоновке данных объекта.

Замечание:
Gdb, и поэтому отладчик Qt Creator, работают с оптимизированной сборкой на Linux и Mac OS X. Тем не менее, оптимизация может привести к изменению порядка инструкций и иногда даже к полному удалению некоторых локальных переменных. В этом случае вид Локальные и наблюдаемые переменные может показывать неожиданные данные.
Отладочная информация, предоставляемая gcc не включает достаточной информации о времени, когда переменная инициализируется. Поэтому, Qt Creator не может сказать является ли содержимое начальной переменной «настоящими данными» или «начальным шумом». Если QObject появляется неинициализированным, его значение будет указано как «вне области». Тем не менее, не все неинициализированные объекты могут быть распознаны таким образом.

Вид Локальные и наблюдаемые переменные также предоставляет доступ к наиболее мощной особенности отладчика: полное отображение данных, принадлежащих базовым объектам Qt. Для включения этой особенности, выберите Использовать помощник отладчика в меню Отладка. Вид Локальные и наблюдаемые переменные будут автоматически переупорядочены для отображения высокоуровневого вида объектов. Например, в случае с QObject, вместо отображения указателя на некоторую закрытую структуру данных, вы увидите список потомков, сигналы и слоты.

Аналогично, вместо отображения множества указателей и целых чисел, отладчик Qt Creator покажет содержимое QHash или QMap в упорядоченном виде. Также отладчик покажет данные доступа для QFileInfo и предоставит доступ к «реальному» содержимому QVariant.

Вид Локальные и наблюдаемые переменные может быть использован для изменения содержимого переменной простого типа данных, такого как int или float, когда программа прервана. Чтобы сделать это, щёлкните на столбце Значение, исправьте значение в встроенном редакторе и нажмите Enter (или Return).

Замечание: Набор наблюдаемых переменных сохраняется в вашей сессии.

Модули

По умолчанию, вид Модули спрятан, так как он полезен только с экспериментальным средством отложенной загрузки отладочной информации. Вы можете включить это свойство выбрав Быстрый запуск отладчика

С этим свойством, отладочная информация из библиотеки Qt не загружается при запуске программы, таким образом уменьшая время запуска для некоторых приложений. В этом случае вы можете использовать вид Модули для загрузки этой информации вручную при необходимости.

Замечание: В этом случае некоторые точки останова не могут быть вызваны отладчиком.

Дизассемдлер и Регисты

По умолчанию, виды Дизассемблер и Регистры спрятаны. Вид Дизассемблер отображает дизассемблированный код для текущей функции; вид Registers отображает текущее состояние регистров CPU. Оба вида полезны для низкоуровневых команд, таких как Перейти на одну инструкцию и Перейти через инструкцию.

Библиотека помощника отладчика

При отладке Qt Creator динамически загружает вспомогательную библиотеку в вашу программу. Эта вспомогательная библиотека обеспечивает Qt Creator красивое отображение типов Qt и STL. Пакет Qt SDK уже содержит заранее скомпилированную библиотеку помощника отладчика. Чтобы создать библиотеку помощника отладчика, выберите Параметры. из меню Инструменты и перейдите на закладку Qt 4/Версии Qt. Так как внутренняя компоновка Qt может меняться для разных версий, библиотека помощника отладчика собирается для каждой версии Qt.

Пособие по интерфейсу отладчика

В нашем примере TextFinder мы считывали текстовый файл в QString, а замет отображали его в QTextEdit. Предположим, что вы хотите взглянуть на эту строку QString line и посмотреть какую информацию она хранит. Выполните шаги, описанные ниже, чтобы разместить точку останова и просмотреть данные объекта QString.

Qt debug information files что это. Смотреть фото Qt debug information files что это. Смотреть картинку Qt debug information files что это. Картинка про Qt debug information files что это. Фото Qt debug information files что этоУстановка точки останова

Сначала, мы установим точку останова на строке где мы вызываем setPlainText() щёлкнув между номером строки и границей окна. Затем, выберите Начать отладку из меню Отладка или нажмите F5.

Точки останова указываются в виде Точки останова, показанного ниже, в режиме Отладка. Если вы желаете удалить точку останова, просто щёлкните на ней правой кнопкой мыши и выберите Удалить точку останова из контекстного меню.

Qt debug information files что это. Смотреть фото Qt debug information files что это. Смотреть картинку Qt debug information files что это. Картинка про Qt debug information files что это. Фото Qt debug information files что это

Чтобы просмотреть содержимое строки line, взгляните на вид Локальные или наблюдаемые переменные.

Qt debug information files что это. Смотреть фото Qt debug information files что это. Смотреть картинку Qt debug information files что это. Картинка про Qt debug information files что это. Фото Qt debug information files что это

Предположим что мы изменили нашу функцию on_findButton_clicked() чтобы она перемещалась в начало документа и продолжала поиск после того, как курсор достигал конца документа. Эта функциональность может быть добавлена с помощью фрагмента кода, приведённого ниже:

Тем не менее, если вы соберёте и запустите этот код, приложение не будет работать правильно из-за логической ошибки. Чтобы обнаружить эту логическую ошибку, вы можете пройти через код, используя следующие кнопки:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *