qdebug qt что это
Здесь представлены несколько полезных советов чтобы помочь вам с отладкой вашего программного обеспечения основанного на Qt.
Конфигурирование Qt для отладки
При конфигурировании Qt для установки, возможно чтобы обеспечить, что она собрана чтобы включить отладочные символы, которые могут сделать это лёгким для отслеживания ошибок в приложениях и библиотеках. Однако, на некоторых платформах, сборка Qt в отладочном режиме заставляет приложения быть больше, чем желательно.
Mac OS X и Xcode
Величина пространства, занятого отладочными символами сгенерированными GCC, может быть чересчур велико. Тем не менее, с релиза Xcode 2.3 теперь возможно использовать символы Dwarf, которые занимают значительно меньшее пространство. Чтобы включить эту возможность при конфигурировании Qt, передайте опцию -dwarf-2 в конфигурационный скрипт.
Она не включена по умолчанию, поскольку предыдущие версии Xcode не будут работать с флагом компилятора, используемым для реализации этой возможности. Mac OS X 10.5 использует символы dwarf-2 по умолчанию.
Символы dwarf-2 содержат ссылки на исходный код, поэтому размер целевого отладочного приложения хорошо согласуется с размером сборки релиза.
Опции командной строки, распознаваемые Qt
Когда вы запускаете приложение Qt, вы можете задать несколько опций командной строки, которые могут помочь при отладке. Распознаваемые QApplication опции командной строки.
Опция | Описание |
---|---|
-nograb | Приложение никогда не будет захватывать мышь или клавиатуру. Эта опция установлена по умолчанию при запуске программы в отладчике gdb под Linux. |
-dograb | Игнорирует любую неявную или явную опцию -nograb. -dograb выигрывает у -nograb даже когда -nograb является последней в командной строке. |
-sync | Запускает приложение в синхронном режиме X. Синхронный режим заставляет X-сервер выполнять каждый запрос X-клиента незамедлительно и не использовать оптимизацию буфера. Это делает программу удобной для отладки и часто более медленной. Опция -sync правильна только для X11 версии Qt. |
Предупреждающие и отладочные сообщения
Qt включает четыре глобальные функции для записи предупреждающих и отладочного текста. Вы можете использовать их для следующих целей:
Реализация этих функций в Qt печатает текст в вывод stderr под Unix/X11 и Mac OS X. В Windows, если это консольное приложение, текст отправляется в консоль; в противном случае, он отправляется отладчику. Вы можете принять эти функции установив обработчик сообещний используя qInstallMsgHandler().
Если переменная окружения QT_FATAL_WARNINGS установлена, qWarning() завершит работу после распечатки предупреждающего сообщения. Это облегчает получение обратной трассировки в отладчике.
И qDebug() и qWarning() являются инструментами отладки. Их можно скомпилировать определив QT_NO_DEBUG_OUTPUT и QT_NO_WARNING_OUTPUT во время компиляции.
Отладочные функции QObject::dumpObjectTree() и QObject::dumpObjectInfo() часто используется когда приложение выглядит или работает странно. Более полезно, если вы используете именами объектов, чем не используете, но часто полезно даже без имён.
Предоставление поддержки потокового оператора qDebug()
Отладка макросов
Заголовочный файл содержит несколько отладочных макросов и директив #define.
Имеется три важных макроса:
Эти макросы используются для обнаружения ошибок программы, например, так:
Q_ASSERT(), Q_ASSERT_X() и Q_CHECK_PTR() расширяет в ничего, если QT_NO_DEBUG определён во время компиляции. По этой причине, аргументы для этих макросов не имеют каких-либо побочных явлений. Вот неправильное использование Q_CHECK_PTR():
Если этот код скомпилирован с определённым макросом QT_NO_DEBUG, код в выражении Q_CHECK_PTR() не выполняется и alloc возвращает неинициализированный указатель.
Библиотека Qt содержит сотни внутренних проверок, которые печатают предупреждающие сообщения при обнаружении программной ошибки. Поэтому мы рекомендуем чтобы вы использовали отладочную версию Qt при разработке программного обеспечения, основанного на Qt.
Распространённые ошибки
Имеется одна ошибка, которая является такой распространённой, что она заслуживает упоминания здесь: если вы включите макрос Q_OBJECT в декларацию класса и запустите мета-объектный компилятор (moc), но забудете прилинковать сгенерированный moc объектный код в ваш исполняемый файл, вы получите очень запутанные сообщения об ошибках. Любая ошибка линковки жалуется на отсутствие vtbl, _vtbl, __vtbl или похожее возможно является результатом этой проблемы.
Qt Documentation
Contents
The QDebug class provides an output stream for debugging information. More.
Public Functions
QDebug(QIODevice *device) | |
QDebug(QString *string) | |
QDebug(QtMsgType type) | |
QDebug(const QDebug &other) | |
QDebug() | |
bool | autoInsertSpaces() const |
QDebug & | maybeQuote(char c = ‘»‘) |
QDebug & | maybeSpace() |
QDebug & | noquote() |
QDebug & | nospace() |
QDebug & | quote() |
QDebug & | resetFormat() |
void | setAutoInsertSpaces(bool b) |
void | setVerbosity(int verbosityLevel) |
QDebug & | space() |
void | swap(QDebug &other) |
int | verbosity() const |
QDebug & | operator &list) |
QDebug | operator &vector) |
QDebug | operator &set) |
QDebug | operator &map) |
QDebug | operator &hash) |
QDebug | operator &pair) |
QDebug | operator &flag) |
Detailed Description
The QDebug class provides an output stream for debugging information.
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 Function Documentation
QDebug:: QDebug ( QIODevice *device)
Constructs a debug stream that writes to the given device.
QDebug:: QDebug ( QString *string)
Constructs a debug stream that writes to the given string.
QDebug:: QDebug ( QtMsgType type)
Constructs a debug stream that writes to the handler for the message type specified by type.
QDebug:: QDebug (const QDebug &other)
Constructs a copy of the other debug 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.
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 ( signed short i)
Writes the signed short integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( unsigned short i)
Writes then unsigned short integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( char16_t t)
QDebug &QDebug:: operator ( char32_t t)
QDebug &QDebug:: operator ( signed int i)
Writes the signed integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( unsigned int i)
Writes then unsigned integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( signed long l)
Writes the signed long integer, l, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( unsigned long l)
Writes then unsigned long integer, l, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( qint64 i)
Writes the signed 64-bit integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( quint64 i)
Writes then unsigned 64-bit integer, i, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( float f)
Writes the 32-bit floating point number, f, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator ( double f)
Writes the 64-bit floating point number, f, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator (const char *s)
Writes the ‘\0’-terminated string, s, 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 &s)
Writes the string, 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.
QDebug &QDebug:: operator (const QStringRef &s)
Writes the string, 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.
QDebug &QDebug:: operator ( QLatin1String s)
Writes the string, 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.
QDebug &QDebug:: operator (const QByteArray &b)
Writes the byte array, b, 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 *p)
Writes a pointer, p, to the stream and returns a reference to the stream.
QDebug &QDebug:: operator= (const QDebug &other)
Assigns the other debug stream to this stream and returns a reference to this stream.
Related Non-Members
QDebug operator ( QDebug stream, const QList T > &list)
Writes the contents of list to stream. T needs to support streaming into QDebug.
QDebug operator ( QDebug stream, const QVector T > &vector)
Writes the contents of vector to stream. T needs to support streaming into QDebug.
QDebug operator ( QDebug stream, const QSet T > &set)
Writes the contents of set to stream. T needs to support streaming into QDebug.
Writes the contents of map to stream. Both Key and T need to support streaming into QDebug.
Writes the contents of hash to stream. Both Key and T need to support streaming into QDebug.
Writes the contents of pair to stream. Both T1 and T2 need to support streaming into QDebug.
QDebug operator ( QDebug stream, const QFlags T > &flag)
Writes flag to stream.
This function was introduced in Qt 4.7.
В© 2017 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 Documentation
Contents
The QDebug class provides an output stream for debugging information. More.
Public Functions
QDebug(QIODevice * device) | |
QDebug(QString * string) | |
QDebug(QtMsgType type) | |
QDebug(const QDebug & other) | |
QDebug() | |
QDebug & | maybeSpace() |
QDebug & | nospace() |
QDebug & | space() |
QDebug & | operator QDebug ( QIODevice * device) Constructs a debug stream that writes to the given device. QDebug:: QDebug ( QString * string)Constructs a debug stream that writes to the given string. QDebug:: QDebug ( QtMsgType type)Constructs a debug stream that writes to the handler for the message type specified by type. QDebug:: QDebug (const QDebug & other)Constructs a copy of the other debug stream. QDebug::Flushes any pending data to be written and destroys the debug stream. QDebug & QDebug:: maybeSpace ()Writes a space character to the debug stream, depending on the last character sent to the stream, and returns a reference to the stream. If the last character was a space character, this function writes a space character to the stream; otherwise, no characters are written to the stream. QDebug & QDebug:: nospace ()Clears the stream’s internal flag that records whether the last character was a space and returns a reference to the stream. QDebug & QDebug:: space ()Writes a space character to the debug stream and returns a reference to the stream. The stream will record that the last character sent to the stream was a space. QDebug & QDebug:: operator ( QChar t)Writes the character, t, to the stream and returns a reference to the stream. 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 ( signed short i)Writes the signed short integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( unsigned short i)Writes then unsigned short integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( signed int i)Writes the signed integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( unsigned int i)Writes then unsigned integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( signed long l)Writes the signed long integer, l, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( unsigned long l)Writes then unsigned long integer, l, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( qint64 i)Writes the signed 64-bit integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( quint64 i)Writes then unsigned 64-bit integer, i, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( float f)Writes the 32-bit floating point number, f, to the stream and returns a reference to the stream. QDebug & QDebug:: operator ( double f)Writes the 64-bit floating point number, f, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const char * s)Writes the ‘\0’-terminated string, s, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const QString & s)Writes the string, s, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const QStringRef & s)Writes the string reference, s, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const QLatin1String & s)Writes the Latin1-encoded string, s, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const QByteArray & b)Writes the byte array, b, to the stream and returns a reference to the stream. QDebug & QDebug:: operator (const void * p)Writes a pointer, p, to the stream and returns a reference to the stream. QDebug & QDebug:: operator= (const QDebug & other)Assigns the other debug stream to this stream and returns a reference to this stream. В© 2016 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.
|