Qt ����������� ��������� linux

Содержание
  1. Qt — трудности перевода
  2. Исходная программа
  3. Шаг 1. Указание всех строк, для которых требуется сделать перевод
  4. Шаг 2. Создание перевода
  5. Шаг 3. Загрузка файлов переводов в приложении.
  6. Дополнительные текстовые строки
  7. Динамический перевод
  8. Qt Documentation
  9. Contents
  10. Types
  11. Functions
  12. Macros
  13. Detailed Description
  14. Types
  15. Functions
  16. Macros
  17. Type Documentation
  18. typedef QFunctionPointer
  19. typedef QtMessageHandler
  20. enum QtMsgType
  21. typedef qint8
  22. typedef qint16
  23. typedef qint32
  24. typedef qint64
  25. typedef qintptr
  26. typedef qlonglong
  27. typedef qptrdiff
  28. typedef qreal
  29. [alias] qsizetype
  30. typedef quint8
  31. typedef quint16
  32. typedef quint32
  33. typedef quint64
  34. typedef quintptr
  35. typedef qulonglong
  36. typedef uchar
  37. typedef uint
  38. typedef ulong
  39. typedef ushort
  40. Function Documentation
  41. QString qEnvironmentVariable (const char *varName)
  42. QString qEnvironmentVariable (const char *varName, const QString &defaultValue)
  43. template T qAbs (const T &t)
  44. template typename std::add_const T > ::type & qAsConst ( T &t)
  45. template void qAsConst (const T &&t)
  46. template const T & qBound (const T &min, const T &val, const T &max)
  47. template auto qConstOverload ( T memberFunctionPointer)
  48. QString qEnvironmentVariable (const char *varName)
  49. QString qEnvironmentVariable (const char *varName, const QString &defaultValue)
  50. int qEnvironmentVariableIntValue (const char *varName, bool *ok = nullptr)
  51. bool qEnvironmentVariableIsEmpty (const char *varName)
  52. bool qEnvironmentVariableIsSet (const char *varName)
  53. template T qExchange ( T &obj, U &&newValue)
  54. quint32 qFloatDistance ( float a, float b)
  55. quint64 qFloatDistance ( double a, double b)
  56. QString qFormatLogMessage ( QtMsgType type, const QMessageLogContext &context, const QString &str)
  57. int qFpClassify ( double val)
  58. bool qFuzzyCompare ( double p1, double p2)
  59. bool qFuzzyCompare ( float p1, float p2)
  60. bool qFuzzyIsNull ( double d)
  61. bool qFuzzyIsNull ( float f)
  62. double qInf ()
  63. QtMessageHandler qInstallMessageHandler ( QtMessageHandler handler)
  64. bool qIsFinite ( double d)
  65. bool qIsFinite ( float f)
  66. bool qIsInf ( double d)
  67. bool qIsInf ( float f)
  68. bool qIsNaN ( double d)
  69. bool qIsNaN ( float f)
  70. template const T & qMax (const T &a, const T &b)
  71. template const T & qMin (const T &a, const T &b)
  72. template auto qNonConstOverload ( T memberFunctionPointer)
  73. template auto qOverload ( T functionPointer)
  74. double qQNaN ()
  75. qint64 qRound64 ( double d)
  76. qint64 qRound64 ( float d)
  77. int qRound ( double d)
  78. int qRound ( float d)
  79. double qSNaN ()
  80. void qSetMessagePattern (const QString &pattern)
  81. const char * qVersion ()
  82. template T * q_check_ptr ( T *p)
  83. QByteArray qgetenv (const char *varName)
  84. bool qputenv (const char *varName, const QByteArray &value)
  85. QString qtTrId (const char *id, int n = -1)
  86. bool qunsetenv (const char *varName)
  87. Macro Documentation
  88. QT_DEPRECATED_WARNINGS
  89. QT_DISABLE_DEPRECATED_BEFORE
  90. QT_NO_DEPRECATED_WARNINGS
  91. QT_POINTER_SIZE
  92. QT_REQUIRE_VERSION ( int argc, char **argv, const char *version)
  93. QT_TRANSLATE_NOOP3 (context, sourceText, disambiguation)
  94. QT_TRANSLATE_NOOP (context, sourceText)
  95. QT_TRANSLATE_N_NOOP3 (context, sourceText, comment)
  96. QT_TRANSLATE_N_NOOP (context, sourceText)
  97. QT_TRID_NOOP (id)
  98. QT_TR_NOOP (sourceText)
  99. QT_TR_N_NOOP (sourceText)
  100. QT_VERSION
  101. QT_VERSION_CHECK
  102. QT_VERSION_STR
  103. void Q_ASSERT ( bool test)
  104. void Q_ASSERT_X ( bool test, const char *where, const char *what)
  105. void Q_ASSUME ( bool expr)
  106. Q_BIG_ENDIAN
  107. Q_BYTE_ORDER
  108. Q_CC_BOR
  109. Q_CC_CDS
  110. Q_CC_CLANG
  111. Q_CC_COMEAU
  112. Q_CC_DEC
  113. Q_CC_EDG
  114. Q_CC_GHS
  115. Q_CC_GNU
  116. Q_CC_HIGHC
  117. Q_CC_HPACC
  118. Q_CC_INTEL
  119. Q_CC_KAI
  120. Q_CC_MIPS
  121. Q_CC_MSVC
  122. Q_CC_OC
  123. Q_CC_PGI
  124. Q_CC_SUN
  125. Q_CC_SYM
  126. Q_CC_USLC
  127. Q_CC_WAT
  128. void Q_CHECK_PTR ( void *pointer)
  129. Q_DECLARE_TYPEINFO (Type, Flags)
  130. Q_DECL_CONSTEXPR
  131. Q_DECL_EXPORT
  132. Q_DECL_IMPORT
  133. Q_DECL_NOEXCEPT
  134. Q_DECL_NOEXCEPT_EXPR (x)
  135. Q_DECL_NOTHROW
  136. Q_DECL_RELAXED_CONSTEXPR
  137. void Q_FALLTHROUGH
  138. Q_FOREACH (variable, container)
  139. Q_FOREVER
  140. Q_FORWARD_DECLARE_CF_TYPE (type)
  141. Q_FORWARD_DECLARE_MUTABLE_CF_TYPE (type)
  142. Q_FORWARD_DECLARE_OBJC_CLASS (classname)
  143. const char * Q_FUNC_INFO
  144. qint64 Q_INT64_C (literal)
  145. Q_LIKELY (expr)
  146. Q_LITTLE_ENDIAN

Qt — трудности перевода

Исходная программа

Пусть у нас есть простая программа:

  1. #include
  2. #include
  3. int main( int argc, char *argv[]) <
  4. QApplication app(argc, argv);
  5. QLabel label( «Hello, World!» );
  6. label.show();
  7. return app.exec();
  8. >

* This source code was highlighted with Source Code Highlighter .

Все что она делает — создает окно с надписью «Hello,World!». Сделаем для нее перевод на русский язык.

Шаг 1. Указание всех строк, для которых требуется сделать перевод

Все строки, которые увидит пользователь должны быть обработаны функциями QObject::tr() или QcoreApplication::translate().
У всех классов Qt, наследуемых от QObject, есть функция-член tr(). Так как мы работаем со строкой в глобальной функции которая не относится ни к какому классу, то используем функцию translate(), которая позволяет указать контекст перевода, то есть класс, к которому он относится (в данном случае — QLabel).

  1. #include
  2. #include
  3. int main( int argc, char *argv[]) <
  4. QApplication app(argc, argv);
  5. QLabel label(app.translate( «QLabel» , «Hello, World!» ));
  6. label.show();
  7. return app.exec();
  8. >

* This source code was highlighted with Source Code Highlighter .

В фунцкиях tr() и translate() после переводимой строки можно указать комментарий, который будет показан переводчику во время перевода приложения на другой языка. Комментарии используются для устранения двусмысленности.
Если вам потребуется перевести текст, который находится вне функции, есть два макроса для помощи: QT_TR_NOOP() и QT_TRANSLATE_NOOP(), аналогичные tr() и translate(). Они незаметно помечают текст для извлечения утилитой lupdate, про которую мы поговорим ниже:

  1. static const char *greeting_strings[] = <
  2. QT_TR_NOOP( «Hello» ),
  3. QT_TR_NOOP( «Goodbye» )
  4. >;
  5. static const char *greeting_strings[] = <
  6. QT_TRANSLATE_NOOP( «HelloWidget» , «Hello» ),
  7. QT_TRANSLATE_NOOP( «HelloWidget» , «Goodbye» )
  8. >;

* This source code was highlighted with Source Code Highlighter .

При отключении автоматического преобразования из const char * в QString путем компиляции программы с определенным макросом QT_NO_CAST_FROM_ASCII можно найти все строки, которые пропустили.
Когда в середину строки нам понадобится вставлять значения каких-либо переменных, лучше всего использовать функцию arg(). Например, при копировании файлов мы могли бы отображать ход процесса следующим образом:

Если потребуется изменить порядок аргументов при переводе, то при переводе надо будет поменять переменные с символом % местами, например, вот так:

«Копируем файл %3. %1 из %2 файлов скопировано»

Переписывать программу из-за этого не потребуется.

Шаг 2. Создание перевода

После того как мы использовали tr() по всему приложению, надо создать перевод текста. Перевод текста так же содержит 3 шага:

  1. Запуск lupdate для извлечения переводимого текста из исходного кода приложения Qt на C++, создавая файл сообщений для переводчиков (файл .ts). Утилита распознает конструкторы tr() и translate() и макросы QT_TR*_NOOP(), описанные выше, и производит файлы .ts (обычно один на каждый язык).
  2. Обеспечение переводов для исходных текстов в файле .ts, используя Qt Linguist. Так как файлы .ts в формате XML, их можно также отредактировать вручную.
  3. Запуск lrelease для получения легкого файла сообщений (файл .qm) из файла .ts, удобного только для конечного пользования. Думайте о файлах .ts как об «исходных файлах», и о файлах .qm как об «объектных файлах». Переводчик редактирует файлы .ts, но пользователям нашего приложения требуются только файлы .qm. Оба типа файлов не зависят от платформы и локали.

Обычно надо повторять эти шаги для каждого выпуска приложения. Утилита lupdate делает все возможное по повторному использованию переводов от предыдущих релизов.
Перед запуском lupdate, вам потребуется подготовить файл проектов. Вот как будет выглядеть наш файл проекта (файл helloworld.pro):

TEMPLATE = app
TARGET = release
DEPENDPATH +=.
INCLUDEPATH +=.
SOURCES += main.cpp
TRANSLATIONS += helloworld_ru.ts

Когда вы запускаете lupdate или lrelease, вы должны предоставить имя файла проекта в качестве аргумента командной строки.

Шаг 3. Загрузка файлов переводов в приложении.

В нашем приложении мы должны загрузить QTranslator::load() файлы используя QcoreApplication::installTranslator(). Окончательная версия программы примет вид:

  1. #include
  2. #include
  3. int main( int argc, char *argv[]) <
  4. QApplication app(argc, argv);
  5. QTranslator myTranslator;
  6. myTranslator.load( «helloworld_» + QLocale::system().name());
  7. app.installTranslator(&myTranslator);
  8. QLabel label(app.translate( «QLabel» , «Hello, World!» ));
  9. label.show();
  10. return app.exec();
  11. >

* This source code was highlighted with Source Code Highlighter .

Мы создаем объект QTranslator, загружаем в него файл перевода с помощью функции load(). В ней мы указываем начало имени файла нашего перевода. По умолчанию файлы переводов ищутся в папке с программой, но можно указать любую директорию, передав ее имя в качестве второго параметра функции. Расширение «.qm» будет добавлено автоматически. Функция Qlocale::system().name() возвращает имя текущей локали, в моем случае это было ru_RU.UTF-8. Порядок поиска файла переводов функцией load() будет следующим:

  1. helloworld_ru_RU.UTF-8.qm
  2. helloworld_ru_RU.UTF-8
  3. helloworld_ru_RU.qm
  4. helloworld_ru_RU
  5. helloworld_ru.qm
  6. helloworld_ru
  7. helloworld.qm
  8. helloworld

Правда когда я попробовал загрузить таким образом файл переводов в Windows XP, у меня ничего не вышло. Оказалось, что (по крайней мере у меня так) функция Qlocale::system().name() все время возвращала значение «С». Поэтому стоит предусмотреть дополнительный способ указания языка интерфейса приложения, например, через диалог настроек программы или параметры командной строки.

Вот и все, наше приложение переведено на русский язык, но есть еще парочка моментов, о которых стоит упомянуть в данной статье.

Дополнительные текстовые строки

Qt содержит внутри около 400 строк, которые так же должны быть переведены на языки которые нам необходимы. В директории $QTDIR/translations можно найти файлы переводов для французского, немецкого и упрощенного китайского, так же как и шаблоны для перевода на другие языки. (Эта директория так же содержит некоторые дополнительные неподдерживаемые переводы, которые могут быть полезны, например, перевод на русский язык).
Обычно эти переводы подгружают так же в фунции main():

  1. int main( int argc, char *argv[])
  2. <
  3. .
  4. QTranslator qtTranslator;
  5. qtTranslator.load( «qt_» + QLocale::system().name(),
  6. QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  7. app.installTranslator(&qtTranslator);
  8. .
  9. >

* This source code was highlighted with Source Code Highlighter .

Обратите внимание на использование QLibraryInfo::location() для обнаружения переводов Qt. Разработчик должен запросить путь к переводам обрабатывая QLibraryInfo::TranslationsPath для этой функции вместо использования переменной среды QTDIR в своих приложениях. Хотя в случаях, когда мы не уверены что у пользователя стоит полная версия Qt, имеет смысл поставлять этот файл переводов вместе с программой и загружать его из директории программы (или любой другой на выбор).

Динамический перевод

Некоторые приложения должны обеспечивать изменения настроек языка пользователя во время работы. Что бы предупредить виджеты об изменениях установленного QTranslators, можно переделать фунцкцию виджета changeEvent() для проверки не является ли событие событием LanguageChange, и обновите текст, отображаемый виджетами, используя функцию tr() обычным способом. Например:

  1. void MyWidget::changeEvent(QEvent * event )
  2. <
  3. if (e->type() == QEvent::LanguageChange) <
  4. titleLabel->setText(tr( «Document Title» ));
  5. .
  6. okPushButton->setText(tr( «&OK» ));
  7. > else
  8. QWidget::changeEvent( event );
  9. >

* This source code was highlighted with Source Code Highlighter .

Все остальные события изменения должны быть обработаны вызовом реализации по умолчанию данной функции.
Список установленных переводов может быть изменен в реакции на событие LocaleChange, или приложение может предоставлять интерфейс пользователю, который позволит ему изменить текущий язык приложения.
Обработчик событий по умолчанию для подклассов QWidget отвечает на событие QEvent::LanguageChange и вызовет эту функцию при необходимости; в других компонентах приложения можно так же заставить виджеты обновить себя отправив им событие LanguageChange.
UPD: Как подсказывает intellinside, классы графического интерфейса пользователя, сгенерированные Qt Designer’ом, имеют функцию retranslateUi(), которую можно вызвать для динамического изменения языка приложения.

Источник

Qt Documentation

Contents

The header file includes the fundamental global declarations. It is included by most other Qt header files. More.

Types

typedef QFunctionPointer
typedef QtMessageHandler
enum QtMsgType
typedef qint8
typedef qint16
typedef qint32
typedef qint64
typedef qintptr
typedef qlonglong
typedef qptrdiff
typedef qreal
(alias) qsizetype
typedef quint8
typedef quint16
typedef quint32
typedef quint64
typedef quintptr
typedef qulonglong
typedef uchar
typedef uint
typedef ulong
typedef ushort

Functions

T qAbs(const T &t)
typename std::add_const ::type & qAsConst(T &t)
void qAsConst(const T &&t)
const T & qBound(const T &min, const T &val, const T &max)
auto qConstOverload(T memberFunctionPointer)
QString qEnvironmentVariable(const char *varName)
QString qEnvironmentVariable(const char *varName, const QString &defaultValue)
int qEnvironmentVariableIntValue(const char *varName, bool *ok = nullptr)
bool qEnvironmentVariableIsEmpty(const char *varName)
bool qEnvironmentVariableIsSet(const char *varName)
T qExchange(T &obj, U &&newValue)
quint32 qFloatDistance(float a, float b)
quint64 qFloatDistance(double a, double b)
QString qFormatLogMessage(QtMsgType type, const QMessageLogContext &context, const QString &str)
int qFpClassify(double val)
bool qFuzzyCompare(double p1, double p2)
bool qFuzzyCompare(float p1, float p2)
bool qFuzzyIsNull(double d)
bool qFuzzyIsNull(float f)
double qInf()
QtMessageHandler qInstallMessageHandler(QtMessageHandler handler)
bool qIsFinite(double d)
bool qIsFinite(float f)
bool qIsInf(double d)
bool qIsInf(float f)
bool qIsNaN(double d)
bool qIsNaN(float f)
const T & qMax(const T &a, const T &b)
const T & qMin(const T &a, const T &b)
auto qNonConstOverload(T memberFunctionPointer)
auto qOverload(T functionPointer)
double qQNaN()
qint64 qRound64(double d)
qint64 qRound64(float d)
int qRound(double d)
int qRound(float d)
double qSNaN()
void qSetMessagePattern(const QString &pattern)
const char * qVersion()
T * q_check_ptr(T *p)
QByteArray qgetenv(const char *varName)
bool qputenv(const char *varName, const QByteArray &value)
QString qtTrId(const char *id, int n = -1)
bool qunsetenv(const char *varName)

Macros

QT_DEPRECATED_WARNINGS
QT_DISABLE_DEPRECATED_BEFORE
QT_NO_DEPRECATED_WARNINGS
QT_POINTER_SIZE
QT_REQUIRE_VERSION(int argc, char **argv, const char *version)
QT_TRANSLATE_NOOP3(context, sourceText, disambiguation)
QT_TRANSLATE_NOOP(context, sourceText)
QT_TRANSLATE_N_NOOP3(context, sourceText, comment)
QT_TRANSLATE_N_NOOP(context, sourceText)
QT_TRID_NOOP(id)
QT_TR_NOOP(sourceText)
QT_TR_N_NOOP(sourceText)
QT_VERSION
QT_VERSION_CHECK
QT_VERSION_STR
void Q_ASSERT(bool test)
void Q_ASSERT_X(bool test, const char *where, const char *what)
void Q_ASSUME(bool expr)
Q_BIG_ENDIAN
Q_BYTE_ORDER
Q_CC_BOR
Q_CC_CDS
Q_CC_CLANG
Q_CC_COMEAU
Q_CC_DEC
Q_CC_EDG
Q_CC_GHS
Q_CC_GNU
Q_CC_HIGHC
Q_CC_HPACC
Q_CC_INTEL
Q_CC_KAI
Q_CC_MIPS
Q_CC_MSVC
Q_CC_OC
Q_CC_PGI
Q_CC_SUN
Q_CC_SYM
Q_CC_USLC
Q_CC_WAT
void Q_CHECK_PTR(void *pointer)
Q_DECLARE_TYPEINFO(Type, Flags)
Q_DECL_CONSTEXPR
Q_DECL_EXPORT
Q_DECL_IMPORT
Q_DECL_NOEXCEPT
Q_DECL_NOEXCEPT_EXPR(x)
Q_DECL_NOTHROW
Q_DECL_RELAXED_CONSTEXPR
void Q_FALLTHROUGH
Q_FOREACH(variable, container)
Q_FOREVER
Q_FORWARD_DECLARE_CF_TYPE(type)
Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(type)
Q_FORWARD_DECLARE_OBJC_CLASS(classname)
const char* Q_FUNC_INFO
qint64 Q_INT64_C(literal)
Q_LIKELY(expr)
Q_LITTLE_ENDIAN
Q_OS_AIX
Q_OS_ANDROID
Q_OS_BSD4
Q_OS_CYGWIN
Q_OS_DARWIN
Q_OS_FREEBSD
Q_OS_HPUX
Q_OS_HURD
Q_OS_IOS
Q_OS_LINUX
Q_OS_LYNX
Q_OS_MAC
Q_OS_MACOS
Q_OS_NETBSD
Q_OS_OPENBSD
Q_OS_OSX
Q_OS_QNX
Q_OS_SOLARIS
Q_OS_TVOS
Q_OS_UNIX
Q_OS_WASM
Q_OS_WATCHOS
Q_OS_WIN32
Q_OS_WIN64
Q_OS_WIN
Q_OS_WINDOWS
Q_OS_WINRT
Q_PROCESSOR_X86
Q_PROCESSOR_S390
Q_PROCESSOR_ALPHA
Q_PROCESSOR_ARM
Q_PROCESSOR_ARM_V5
Q_PROCESSOR_ARM_V6
Q_PROCESSOR_ARM_V7
Q_PROCESSOR_AVR32
Q_PROCESSOR_BLACKFIN
Q_PROCESSOR_IA64
Q_PROCESSOR_MIPS
Q_PROCESSOR_MIPS_32
Q_PROCESSOR_MIPS_64
Q_PROCESSOR_MIPS_I
Q_PROCESSOR_MIPS_II
Q_PROCESSOR_MIPS_III
Q_PROCESSOR_MIPS_IV
Q_PROCESSOR_MIPS_V
Q_PROCESSOR_POWER
Q_PROCESSOR_POWER_32
Q_PROCESSOR_POWER_64
Q_PROCESSOR_RISCV
Q_PROCESSOR_RISCV_32
Q_PROCESSOR_RISCV_64
Q_PROCESSOR_S390_X
Q_PROCESSOR_SH
Q_PROCESSOR_SH_4A
Q_PROCESSOR_SPARC
Q_PROCESSOR_SPARC_V9
Q_PROCESSOR_X86_32
Q_PROCESSOR_X86_64
quint64 Q_UINT64_C(literal)
Q_UNLIKELY(expr)
void Q_UNREACHABLE
Q_UNUSED(name)
foreach(variable, container)
forever
qCritical(const char *message, . )
qDebug(const char *message, . )
qFatal(const char *message, . )
qInfo(const char *message, . )
const char * qPrintable(const QString &str)
const wchar_t * qUtf16Printable(const QString &str)
const char * qUtf8Printable(const QString &str)
qWarning(const char *message, . )

Detailed Description

The global declarations include types, functions and macros.

The type definitions are partly convenience definitions for basic types (some of which guarantee certain bit-sizes on all platforms supported by Qt), partly types related to Qt message handling. The functions are related to generating messages, Qt version handling and comparing and adjusting object values. And finally, some of the declared macros enable programmers to add compiler or platform specific code to their applications, while others are convenience macros for larger operations.

Types

The header file declares several type definitions that guarantee a specified bit-size on all platforms supported by Qt for various basic types, for example qint8 which is a signed char guaranteed to be 8-bit on all platforms supported by Qt. The header file also declares the qlonglong type definition for long long int ( __int64 on Windows).

Several convenience type definitions are declared: qreal for double or float , uchar for unsigned char, uint for unsigned int, ulong for unsigned long and ushort for unsigned short.

Finally, the QtMsgType definition identifies the various messages that can be generated and sent to a Qt message handler; QtMessageHandler is a type definition for a pointer to a function with the signature void myMessageHandler(QtMsgType, const QMessageLogContext &, const char *) . QMessageLogContext class contains the line, file, and function the message was logged at. This information is created by the QMessageLogger class.

Functions

The header file contains several functions comparing and adjusting an object’s value. These functions take a template type as argument: You can retrieve the absolute value of an object using the qAbs() function, and you can bound a given object’s value by given minimum and maximum values using the qBound() function. You can retrieve the minimum and maximum of two given objects using qMin() and qMax() respectively. All these functions return a corresponding template type; the template types can be replaced by any other type.

also contains functions that generate messages from the given string argument: qDebug(), qInfo(), qWarning(), qCritical(), and qFatal(). These functions call the message handler with the given message.

The remaining functions are qRound() and qRound64(), which both accept a double or float value as their argument returning the value rounded up to the nearest integer and 64-bit integer respectively, the qInstallMessageHandler() function which installs the given QtMessageHandler, and the qVersion() function which returns the version number of Qt at run-time as a string.

Macros

The header file provides a range of macros (Q_CC_*) that are defined if the application is compiled using the specified platforms. For example, the Q_CC_SUN macro is defined if the application is compiled using Forte Developer, or Sun Studio C++. The header file also declares a range of macros (Q_OS_*) that are defined for the specified platforms. For example, Q_OS_UNIX which is defined for the Unix-based systems.

The purpose of these macros is to enable programmers to add compiler or platform specific code to their application.

The remaining macros are convenience macros for larger operations: The QT_TR_NOOP(), QT_TRANSLATE_NOOP(), and QT_TRANSLATE_NOOP3() macros provide the possibility of marking strings for delayed translation. QT_TR_N_NOOP(), QT_TRANSLATE_N_NOOP(), and QT_TRANSLATE_N_NOOP3() are numerator dependent variants of these. The Q_ASSERT() and Q_ASSERT_X() enables warning messages of various level of refinement. The Q_FOREACH() and foreach() macros implement Qt’s foreach loop.

The Q_INT64_C() and Q_UINT64_C() macros wrap signed and unsigned 64-bit integer literals in a platform-independent way. The Q_CHECK_PTR() macro prints a warning containing the source code’s file name and line number, saying that the program ran out of memory, if the pointer is nullptr . The qPrintable() and qUtf8Printable() macros represent an easy way of printing text.

The QT_POINTER_SIZE macro expands to the size of a pointer in bytes.

The macros QT_VERSION and QT_VERSION_STR expand to a numeric value or a string, respectively, that specifies the version of Qt that the application is compiled against.

Type Documentation

typedef QFunctionPointer

This is a typedef for void (*)() , a pointer to a function that takes no arguments and returns void.

typedef QtMessageHandler

This is a typedef for a pointer to a function with the following signature:

This typedef was introduced in Qt 5.0.

enum QtMsgType

This enum describes the messages that can be sent to a message handler (QtMessageHandler). You can use the enum to identify and associate the various message types with the appropriate actions.

Constant Value Description
QtDebugMsg 0 A message generated by the qDebug() function.
QtInfoMsg 4 A message generated by the qInfo() function.
QtWarningMsg 1 A message generated by the qWarning() function.
QtCriticalMsg 2 A message generated by the qCritical() function.
QtFatalMsg 3 A message generated by the qFatal() function.
QtSystemMsg QtCriticalMsg В

QtInfoMsg was added in Qt 5.5.

typedef qint8

Typedef for signed char . This type is guaranteed to be 8-bit on all platforms supported by Qt.

typedef qint16

Typedef for signed short . This type is guaranteed to be 16-bit on all platforms supported by Qt.

typedef qint32

Typedef for signed int . This type is guaranteed to be 32-bit on all platforms supported by Qt.

typedef qint64

Typedef for long long int ( __int64 on Windows). This type is guaranteed to be 64-bit on all platforms supported by Qt.

Literals of this type can be created using the Q_INT64_C() macro:

typedef qintptr

Integral type for representing pointers in a signed integer (useful for hashing, etc.).

Typedef for either qint32 or qint64. This type is guaranteed to be the same size as a pointer on all platforms supported by Qt. On a system with 32-bit pointers, qintptr is a typedef for qint32; on a system with 64-bit pointers, qintptr is a typedef for qint64.

Note that qintptr is signed. Use quintptr for unsigned values.

typedef qlonglong

Typedef for long long int ( __int64 on Windows). This is the same as qint64.

typedef qptrdiff

Integral type for representing pointer differences.

Typedef for either qint32 or qint64. This type is guaranteed to be the same size as a pointer on all platforms supported by Qt. On a system with 32-bit pointers, quintptr is a typedef for quint32; on a system with 64-bit pointers, quintptr is a typedef for quint64.

Note that qptrdiff is signed. Use quintptr for unsigned values.

typedef qreal

Typedef for double unless Qt is configured with the -qreal float option.

[alias] qsizetype

This is a type alias for QIntegerForSizeof ::Signed.

Integral type providing Posix’ ssize_t for all platforms.

This type is guaranteed to be the same size as a size_t on all platforms supported by Qt.

Note that qsizetype is signed. Use size_t for unsigned values.

This alias was introduced in Qt 5.10.

typedef quint8

Typedef for unsigned char . This type is guaranteed to be 8-bit on all platforms supported by Qt.

typedef quint16

Typedef for unsigned short . This type is guaranteed to be 16-bit on all platforms supported by Qt.

typedef quint32

Typedef for unsigned int . This type is guaranteed to be 32-bit on all platforms supported by Qt.

typedef quint64

Typedef for unsigned long long int ( unsigned __int64 on Windows). This type is guaranteed to be 64-bit on all platforms supported by Qt.

Literals of this type can be created using the Q_UINT64_C() macro:

typedef quintptr

Integral type for representing pointers in an unsigned integer (useful for hashing, etc.).

Typedef for either quint32 or quint64. This type is guaranteed to be the same size as a pointer on all platforms supported by Qt. On a system with 32-bit pointers, quintptr is a typedef for quint32; on a system with 64-bit pointers, quintptr is a typedef for quint64.

Note that quintptr is unsigned. Use qptrdiff for signed values.

typedef qulonglong

Typedef for unsigned long long int ( unsigned __int64 on Windows). This is the same as quint64.

typedef uchar

Convenience typedef for unsigned char .

typedef uint

Convenience typedef for unsigned int .

typedef ulong

Convenience typedef for unsigned long .

typedef ushort

Convenience typedef for unsigned short .

Function Documentation

QString qEnvironmentVariable (const char *varName)

QString qEnvironmentVariable (const char *varName, const QString &defaultValue)

These functions return the value of the environment variable, varName, as a QString. If no variable varName is found in the environment and defaultValue is provided, defaultValue is returned. Otherwise QString() is returned.

The Qt environment manipulation functions are thread-safe, but this requires that the C library equivalent functions like getenv and putenv are not directly called.

The following table describes how to choose between qgetenv() and qEnvironmentVariable():

Condition Recommendation
Variable contains file paths or user text qEnvironmentVariable()
Windows-specific code qEnvironmentVariable()
Unix-specific code, destination variable is not QString and/or is used to interface with non-Qt APIs qgetenv()
Destination variable is a QString qEnvironmentVariable()
Destination variable is a QByteArray or std::string qgetenv()

Note: on Unix systems, this function may produce data loss if the original string contains arbitrary binary data that cannot be decoded by the locale codec. Use qgetenv() instead for that case. On Windows, this function is lossless.

Note: the variable name varName must contain only US-ASCII characters.

This function was introduced in Qt 5.10.

template T qAbs (const T &t)

Compares t to the 0 of type T and returns the absolute value. Thus if T is double, then t is compared to (double) 0.

template typename std::add_const T > ::type & qAsConst ( T &t)

Returns t cast to const T .

This function is a Qt implementation of C++17’s std::as_const(), a cast function like std::move(). But while std::move() turns lvalues into rvalues, this function turns non-const lvalues into const lvalues. Like std::as_const(), it doesn’t work on rvalues, because it cannot be efficiently implemented for rvalues without leaving dangling references.

Its main use in Qt is to prevent implicitly-shared Qt containers from detaching:

Of course, in this case, you could (and probably should) have declared s as const in the first place:

but often that is not easily possible.

It is important to note that qAsConst() does not copy its argument, it just performs a const_cast (t) . This is also the reason why it is designed to fail for rvalues: The returned reference would go stale too soon. So while this works (but detaches the returned object):

To prevent this construct from compiling (and failing at runtime), qAsConst() has a second, deleted, overload which binds to rvalues.

This function was introduced in Qt 5.7.

template void qAsConst (const T &&t)

This is an overloaded function.

This overload is deleted to prevent a dangling reference in code like

This function was introduced in Qt 5.7.

template const T & qBound (const T &min, const T &val, const T &max)

Returns val bounded by min and max. This is equivalent to qMax(min, qMin(val, max)).

template auto qConstOverload ( T memberFunctionPointer)

Returns the memberFunctionPointer pointer to a constant member function:

This function was introduced in Qt 5.7.

QString qEnvironmentVariable (const char *varName)

QString qEnvironmentVariable (const char *varName, const QString &defaultValue)

int qEnvironmentVariableIntValue (const char *varName, bool *ok = nullptr)

Returns the numerical value of the environment variable varName. If ok is not null, sets *ok to true or false depending on the success of the conversion.

except that it’s much faster, and can’t throw exceptions.

Note: there’s a limit on the length of the value, which is sufficient for all valid values of int, not counting leading zeroes or spaces. Values that are too long will either be truncated or this function will set ok to false .

This function was introduced in Qt 5.5.

bool qEnvironmentVariableIsEmpty (const char *varName)

Returns whether the environment variable varName is empty.

except that it’s potentially much faster, and can’t throw exceptions.

This function was introduced in Qt 5.1.

bool qEnvironmentVariableIsSet (const char *varName)

Returns whether the environment variable varName is set.

except that it’s potentially much faster, and can’t throw exceptions.

This function was introduced in Qt 5.1.

template T qExchange ( T &obj, U &&newValue)

Replaces the value of obj with newValue and returns the old value of obj.

This is Qt’s implementation of std::exchange(). It differs from std::exchange() only in that it is constexpr already in C++14, and available on all supported compilers.

Here is how to use qExchange() to implement move constructors:

For members of class type, we can use std::move(), as their move-constructor will do the right thing. But for scalar types such as raw pointers or integer type, move is the same as copy, which, particularly for pointers, is not what we expect. So, we cannot use std::move() for such types, but we can use std::exchange()/qExchange() to make sure the source object’s member is already reset by the time we get to the initialization of our next data member, which might come in handy if the constructor exits with an exception.

Here is how to use qExchange() to write a loop that consumes the collection it iterates over:

Which is equivalent to the following, much more verbose code:

This is perfectly safe, as the for-loop keeps the result of qExchange() alive for as long as the loop runs, saving the declaration of a temporary variable. Be aware, though, that qExchange() returns a non-const object, so Qt containers may detach.

This function was introduced in Qt 5.14.

quint32 qFloatDistance ( float a, float b)

Returns the number of representable floating-point numbers between a and b.

This function provides an alternative way of doing approximated comparisons of floating-point numbers similar to qFuzzyCompare(). However, it returns the distance between two numbers, which gives the caller a possibility to choose the accepted error. Errors are relative, so for instance the distance between 1.0E-5 and 1.00001E-5 will give 110, while the distance between 1.0E36 and 1.00001E36 will give 127.

This function is useful if a floating point comparison requires a certain precision. Therefore, if a and b are equal it will return 0. The maximum value it will return for 32-bit floating point numbers is 4,278,190,078. This is the distance between -FLT_MAX and +FLT_MAX .

The function does not give meaningful results if any of the arguments are Infinite or NaN . You can check for this by calling qIsFinite().

The return value can be considered as the «error», so if you for instance want to compare two 32-bit floating point numbers and all you need is an approximated 24-bit precision, you can use this function like this:

This function was introduced in Qt 5.2.

quint64 qFloatDistance ( double a, double b)

Returns the number of representable floating-point numbers between a and b.

This function serves the same purpose as qFloatDistance(float, float) , but returns the distance between two double numbers. Since the range is larger than for two float numbers ( [-DBL_MAX,DBL_MAX] ), the return type is quint64.

This function was introduced in Qt 5.2.

QString qFormatLogMessage ( QtMsgType type, const QMessageLogContext &context, const QString &str)

Generates a formatted string out of the type, context, str arguments.

qFormatLogMessage returns a QString that is formatted according to the current message pattern. It can be used by custom message handlers to format output similar to Qt’s default message handler.

The function is thread-safe.

This function was introduced in Qt 5.4.

int qFpClassify ( double val)

Classifies a floating-point value.

The return values are defined in : returns one of the following, determined by the floating-point class of val:

  • FP_NAN not a number
  • FP_INFINITE infinities (positive or negative)
  • FP_ZERO zero (positive or negative)
  • FP_NORMAL finite with a full mantissa
  • FP_SUBNORMAL finite with a reduced mantissa

bool qFuzzyCompare ( double p1, double p2)

Compares the floating point value p1 and p2 and returns true if they are considered equal, otherwise false .

Note that comparing values where either p1 or p2 is 0.0 will not work, nor does comparing values where one of the values is NaN or infinity. If one of the values is always 0.0, use qFuzzyIsNull instead. If one of the values is likely to be 0.0, one solution is to add 1.0 to both values.

The two numbers are compared in a relative way, where the exactness is stronger the smaller the numbers are.

This function was introduced in Qt 4.4.

bool qFuzzyCompare ( float p1, float p2)

Compares the floating point value p1 and p2 and returns true if they are considered equal, otherwise false .

The two numbers are compared in a relative way, where the exactness is stronger the smaller the numbers are.

This function was introduced in Qt 4.4.

bool qFuzzyIsNull ( double d)

Returns true if the absolute value of d is within 0.000000000001 of 0.0.

This function was introduced in Qt 4.4.

bool qFuzzyIsNull ( float f)

Returns true if the absolute value of f is within 0.00001f of 0.0.

This function was introduced in Qt 4.4.

double qInf ()

Returns the bit pattern for an infinite number as a double.

QtMessageHandler qInstallMessageHandler ( QtMessageHandler handler)

Installs a Qt message handler which has been defined previously. Returns a pointer to the previous message handler.

The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur. Qt built in release mode also contains such warnings unless QT_NO_WARNING_OUTPUT and/or QT_NO_DEBUG_OUTPUT have been set during compilation. If you implement your own message handler, you get total control of these messages.

The default message handler prints the message to the standard output under X11 or to the debugger under Windows. If it is a fatal message, the application aborts immediately.

Only one message handler can be defined, since this is usually done on an application-wide basis to control debug output.

To restore the message handler, call qInstallMessageHandler(0) .

This function was introduced in Qt 5.0.

bool qIsFinite ( double d)

Returns true if the double d is a finite number.

bool qIsFinite ( float f)

Returns true if the float f is a finite number.

bool qIsInf ( double d)

Returns true if the double d is equivalent to infinity.

bool qIsInf ( float f)

Returns true if the float f is equivalent to infinity.

bool qIsNaN ( double d)

Returns true if the double d is not a number (NaN).

bool qIsNaN ( float f)

Returns true if the float f is not a number (NaN).

template const T & qMax (const T &a, const T &b)

Returns the maximum of a and b.

template const T & qMin (const T &a, const T &b)

Returns the minimum of a and b.

template auto qNonConstOverload ( T memberFunctionPointer)

Returns the memberFunctionPointer pointer to a non-constant member function:

This function was introduced in Qt 5.7.

template auto qOverload ( T functionPointer)

Returns a pointer to an overloaded function. The template parameter is the list of the argument types of the function. functionPointer is the pointer to the (member) function:

If a member function is also const-overloaded qConstOverload and qNonConstOverload need to be used.

qOverload() requires C++14 enabled. In C++11-only code, the helper classes QOverload, QConstOverload, and QNonConstOverload can be used directly:

Note: Qt detects the necessary C++14 compiler support by way of the feature test recommendations from C++ Committee’s Standing Document 6.

This function was introduced in Qt 5.7.

double qQNaN ()

Returns the bit pattern of a quiet NaN as a double.

qint64 qRound64 ( double d)

Rounds d to the nearest 64-bit integer.

Rounds half up (e.g. 0.5 -> 1, -0.5 -> 0).

qint64 qRound64 ( float d)

Rounds d to the nearest 64-bit integer.

Rounds half up (e.g. 0.5f -> 1, -0.5f -> 0).

int qRound ( double d)

Rounds d to the nearest integer.

Rounds half up (e.g. 0.5 -> 1, -0.5 -> 0).

int qRound ( float d)

Rounds d to the nearest integer.

Rounds half up (e.g. 0.5f -> 1, -0.5f -> 0).

double qSNaN ()

Returns the bit pattern of a signalling NaN as a double.

void qSetMessagePattern (const QString &pattern)

Changes the output of the default message handler.

Allows to tweak the output of qDebug(), qInfo(), qWarning(), qCritical(), and qFatal(). The category logging output of qCDebug(), qCInfo(), qCWarning(), and qCCritical() is formatted, too.

Following placeholders are supported:

Placeholder Description
% QCoreApplication::applicationName()
% Logging category
% Path to source file
% Function
% Line in source file
% The actual message
% QCoreApplication::applicationPid()
% The system-wide ID of current thread (if it can be obtained)
% A pointer to the current QThread (result of QThread::currentThread())
% «debug», «warning», «critical» or «fatal»
% time of the message, in seconds since the process started (the token «process» is literal)
% the time of the message, in seconds since the system boot if that can be determined (the token «boot» is literal). If the time since boot could not be obtained, the output is indeterminate (see QElapsedTimer::msecsSinceReference()).
% system time when the message occurred, formatted by passing the format to QDateTime::toString(). If the format is not specified, the format of Qt::ISODate is used.
% A backtrace with the number of frames specified by the optional depth parameter (defaults to 5), and separated by the optional separator parameter (defaults to «|»). This expansion is available only on some platforms (currently only platfoms using glibc). Names are only known for exported functions. If you want to see the name of every function in your application, use QMAKE_LFLAGS += -rdynamic . When reading backtraces, take into account that frames might be missing due to inlining or tail call optimization.

You can also use conditionals on the type of the message using % , % % , % or % followed by an % . What is inside the % and % will only be printed if the type matches.

Finally, text inside % . % is only printed if the category is not the default one.

The pattern can also be changed at runtime by setting the QT_MESSAGE_PATTERN environment variable; if both qSetMessagePattern() is called and QT_MESSAGE_PATTERN is set, the environment variable takes precedence.

Note: The message pattern only applies to unstructured logging, such as the default stderr output. Structured logging such as systemd will record the message as is, along with as much structured information as can be captured.

Custom message handlers can use qFormatLogMessage() to take pattern into account.

This function was introduced in Qt 5.0.

const char * qVersion ()

Returns the version number of Qt at run-time as a string (for example, «4.1.2»). This may be a different version than the version the application was compiled against.

template T * q_check_ptr ( T *p)

This can be used as an inline version of Q_CHECK_PTR.

QByteArray qgetenv (const char *varName)

Returns the value of the environment variable with name varName as a QByteArray. If no variable by that name is found in the environment, this function returns a default-constructed QByteArray.

The Qt environment manipulation functions are thread-safe, but this requires that the C library equivalent functions like getenv and putenv are not directly called.

Note: on desktop Windows, qgetenv() may produce data loss if the original string contains Unicode characters not representable in the ANSI encoding. Use qEnvironmentVariable() instead. On Unix systems, this function is lossless.

bool qputenv (const char *varName, const QByteArray &value)

This function sets the value of the environment variable named varName. It will create the variable if it does not exist. It returns 0 if the variable could not be set.

Calling qputenv with an empty value removes the environment variable on Windows, and makes it set (but empty) on Unix. Prefer using qunsetenv() for fully portable behavior.

Note: qputenv() was introduced because putenv() from the standard C library was deprecated in VC2005 (and later versions). qputenv() uses the replacement function in VC, and calls the standard C library’s implementation on all other platforms.

QString qtTrId (const char *id, int n = -1)

The qtTrId function finds and returns a translated string.

Returns a translated string identified by id. If no matching string is found, the id itself is returned. This should not happen under normal conditions.

If n >= 0, all occurrences of %n in the resulting string are replaced with a decimal representation of n. In addition, depending on n‘s value, the translation text may vary.

Meta data and comments can be passed as documented for QObject::tr(). In addition, it is possible to supply a source string template like that:

Creating QM files suitable for use with this function requires passing the -idbased option to the lrelease tool.

Warning: This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.

This function was introduced in Qt 4.6.

bool qunsetenv (const char *varName)

This function deletes the variable varName from the environment.

Returns true on success.

This function was introduced in Qt 5.1.

Macro Documentation

QT_DEPRECATED_WARNINGS

Since Qt 5.13, this macro has no effect. In Qt 5.12 and before, if this macro is defined, the compiler will generate warnings if any API declared as deprecated by Qt is used.

QT_DISABLE_DEPRECATED_BEFORE

This macro can be defined in the project file to disable functions deprecated in a specified version of Qt or any earlier version. The default version number is 5.0, meaning that functions deprecated in or before Qt 5.0 will not be included.

For instance, when using a future release of Qt 5, set QT_DISABLE_DEPRECATED_BEFORE=0x050100 to disable functions deprecated in Qt 5.1 and earlier. In any release, set QT_DISABLE_DEPRECATED_BEFORE=0x000000 to enable all functions, including the ones deprecated in Qt 5.0.

QT_NO_DEPRECATED_WARNINGS

This macro can be used to suppress deprecation warnings that would otherwise be generated when using deprecated APIs.

This function was introduced in Qt 5.13.

QT_POINTER_SIZE

Expands to the size of a pointer in bytes (4 or 8). This is equivalent to sizeof(void *) but can be used in a preprocessor directive.

QT_REQUIRE_VERSION ( int argc, char **argv, const char *version)

This macro can be used to ensure that the application is run against a recent enough version of Qt. This is especially useful if your application depends on a specific bug fix introduced in a bug-fix release (e.g., 4.0.2).

The argc and argv parameters are the main() function’s argc and argv parameters. The version parameter is a string literal that specifies which version of Qt the application requires (e.g., «4.0.2»).

QT_TRANSLATE_NOOP3 (context, sourceText, disambiguation)

Marks the UTF-8 encoded string literal sourceText for delayed translation in the given context with the given disambiguation. The context is typically a class and also needs to be specified as a string literal. The string literal disambiguation should be a short semantic tag to tell apart otherwise identical strings.

The macro tells lupdate to collect the string, and expands to an anonymous struct of the two string literals passed as sourceText and disambiguation.

This function was introduced in Qt 4.4.

QT_TRANSLATE_NOOP (context, sourceText)

Marks the UTF-8 encoded string literal sourceText for delayed translation in the given context. The context is typically a class name and also needs to be specified as a string literal.

The macro tells lupdate to collect the string, and expands to sourceText itself.

QT_TRANSLATE_N_NOOP3 (context, sourceText, comment)

Marks the UTF-8 encoded string literal sourceText for numerator dependent delayed translation in the given context with the given comment. The context is typically a class and also needs to be specified as a string literal. The string literal comment should be a short semantic tag to tell apart otherwise identical strings.

The macro tells lupdate to collect the string, and expands to an anonymous struct of the two string literals passed as sourceText and comment.

This function was introduced in Qt 5.12.

QT_TRANSLATE_N_NOOP (context, sourceText)

Marks the UTF-8 encoded string literal sourceText for numerator dependent delayed translation in the given context. The context is typically a class name and also needs to be specified as a string literal.

The macro tells lupdate to collect the string, and expands to sourceText itself.

This function was introduced in Qt 5.12.

QT_TRID_NOOP (id)

The QT_TRID_NOOP macro marks an id for dynamic translation.

The only purpose of this macro is to provide an anchor for attaching meta data like to qtTrId().

The macro expands to id.

This function was introduced in Qt 4.6.

QT_TR_NOOP (sourceText)

Marks the UTF-8 encoded string literal sourceText for delayed translation in the current context (class).

The macro tells lupdate to collect the string, and expands to sourceText itself.

The macro QT_TR_NOOP_UTF8() is identical and obsolete; this applies to all other _UTF8 macros as well.

QT_TR_N_NOOP (sourceText)

Marks the UTF-8 encoded string literal sourceText for numerator dependent delayed translation in the current context (class).

The macro tells lupdate to collect the string, and expands to sourceText itself.

The macro expands to sourceText.

This function was introduced in Qt 5.12.

QT_VERSION

This macro expands a numeric value of the form 0xMMNNPP (MM = major, NN = minor, PP = patch) that specifies Qt’s version number. For example, if you compile your application against Qt 4.1.2, the QT_VERSION macro will expand to 0x040102.

You can use QT_VERSION to use the latest Qt features where available.

QT_VERSION_CHECK

Turns the major, minor and patch numbers of a version into an integer, 0xMMNNPP (MM = major, NN = minor, PP = patch). This can be compared with another similarly processed version id.

QT_VERSION_STR

This macro expands to a string that specifies Qt’s version number (for example, «4.1.2»). This is the version against which the application is compiled.

void Q_ASSERT ( bool test)

Prints a warning message containing the source code file name and line number if test is false .

Q_ASSERT() is useful for testing pre- and post-conditions during development. It does nothing if QT_NO_DEBUG was defined during compilation.

If b is zero, the Q_ASSERT statement will output the following message using the qFatal() function:

void Q_ASSERT_X ( bool test, const char *where, const char *what)

Prints the message what together with the location where, the source file name and line number if test is false .

Q_ASSERT_X is useful for testing pre- and post-conditions during development. It does nothing if QT_NO_DEBUG was defined during compilation.

If b is zero, the Q_ASSERT_X statement will output the following message using the qFatal() function:

void Q_ASSUME ( bool expr)

Causes the compiler to assume that expr is true . This macro is useful for improving code generation, by providing the compiler with hints about conditions that it would not otherwise know about. However, there is no guarantee that the compiler will actually use those hints.

This macro could be considered a «lighter» version of Q_ASSERT(). While Q_ASSERT will abort the program’s execution if the condition is false , Q_ASSUME will tell the compiler not to generate code for those conditions. Therefore, it is important that the assumptions always hold, otherwise undefined behaviour may occur.

If expr is a constantly false condition, Q_ASSUME will tell the compiler that the current code execution cannot be reached. That is, Q_ASSUME(false) is equivalent to Q_UNREACHABLE().

In debug builds the condition is enforced by an assert to facilitate debugging.

Note: Q_LIKELY() tells the compiler that the expression is likely, but not the only possibility. Q_ASSUME tells the compiler that it is the only possibility.

This function was introduced in Qt 5.0.

Q_BIG_ENDIAN

This macro represents a value you can compare to the macro Q_BYTE_ORDER to determine the endian-ness of your system. In a big-endian system, the most significant byte is stored at the lowest address. The other bytes follow in decreasing order of significance.

Q_BYTE_ORDER

This macro can be used to determine the byte order your system uses for storing data in memory. i.e., whether your system is little-endian or big-endian. It is set by Qt to one of the macros Q_LITTLE_ENDIAN or Q_BIG_ENDIAN. You normally won’t need to worry about endian-ness, but you might, for example if you need to know which byte of an integer or UTF-16 character is stored in the lowest address. Endian-ness is important in networking, where computers with different values for Q_BYTE_ORDER must pass data back and forth.

Use this macro as in the following examples.

Q_CC_BOR

Defined if the application is compiled using Borland/Turbo C++.

Q_CC_CDS

Defined if the application is compiled using Reliant C++.

Q_CC_CLANG

Defined if the application is compiled using Clang.

Q_CC_COMEAU

Defined if the application is compiled using Comeau C++.

Q_CC_DEC

Defined if the application is compiled using DEC C++.

Q_CC_EDG

Defined if the application is compiled using Edison Design Group C++.

Q_CC_GHS

Defined if the application is compiled using Green Hills Optimizing C++ Compilers.

Q_CC_GNU

Defined if the application is compiled using GNU C++.

Q_CC_HIGHC

Defined if the application is compiled using MetaWare High C/C++.

Q_CC_HPACC

Defined if the application is compiled using HP aC++.

Q_CC_INTEL

Defined if the application is compiled using Intel C++ for Linux, Intel C++ for Windows.

Q_CC_KAI

Defined if the application is compiled using KAI C++.

Q_CC_MIPS

Defined if the application is compiled using MIPSpro C++.

Q_CC_MSVC

Defined if the application is compiled using Microsoft Visual C/C++, Intel C++ for Windows.

Q_CC_OC

Defined if the application is compiled using CenterLine C++.

Q_CC_PGI

Defined if the application is compiled using Portland Group C++.

Q_CC_SUN

Defined if the application is compiled using Forte Developer, or Sun Studio C++.

Q_CC_SYM

Defined if the application is compiled using Digital Mars C/C++ (used to be Symantec C++).

Q_CC_USLC

Defined if the application is compiled using SCO OUDK and UDK.

Q_CC_WAT

Defined if the application is compiled using Watcom C++.

void Q_CHECK_PTR ( void *pointer)

If pointer is nullptr , prints a message containing the source code’s file name and line number, saying that the program ran out of memory and aborts program execution. It throws std::bad_alloc instead if exceptions are enabled.

Q_CHECK_PTR does nothing if QT_NO_DEBUG and QT_NO_EXCEPTIONS were defined during compilation. Therefore you must not use Q_CHECK_PTR to check for successful memory allocations because the check will be disabled in some cases.

Q_DECLARE_TYPEINFO (Type, Flags)

You can use this macro to specify information about a custom type Type. With accurate type information, Qt’s generic containers can choose appropriate storage methods and algorithms.

Flags can be one of the following:

  • Q_PRIMITIVE_TYPE specifies that Type is a POD (plain old data) type with no constructor or destructor, and for which memcpy()ing creates a valid independent copy of the object.
  • Q_MOVABLE_TYPE specifies that Type has a constructor and/or a destructor but can be moved in memory using memcpy() . Note: despite the name, this has nothing to do with move constructors or C++ move semantics.
  • Q_COMPLEX_TYPE (the default) specifies that Type has constructors and/or a destructor and that it may not be moved in memory.

Example of a «primitive» type:

An example of a non-POD «primitive» type is QUuid: Even though QUuid has constructors (and therefore isn’t POD), every bit pattern still represents a valid object, and memcpy() can be used to create a valid independent copy of a QUuid object.

Example of a movable type:

Qt will try to detect the class of a type using std::is_trivial or std::is_trivially_copyable. Use this macro to tune the behavior. For instance many types would be candidates for Q_MOVABLE_TYPE despite not being trivially-copyable. For binary compatibility reasons, QList optimizations are only enabled if there is an explicit Q_DECLARE_TYPEINFO even for trivially-copyable types.

Q_DECL_CONSTEXPR

This macro can be used to declare variable that should be constructed at compile-time, or an inline function that can be computed at compile-time.

It expands to «constexpr» if your compiler supports that C++11 keyword, or to nothing otherwise.

Q_DECL_EXPORT

This macro marks a symbol for shared library export (see Creating Shared Libraries).

Q_DECL_IMPORT

This macro declares a symbol to be an import from a shared library (see Creating Shared Libraries).

Q_DECL_NOEXCEPT

This macro marks a function as never throwing. If the function does nevertheless throw, the behaviour is defined: std::terminate() is called.

The macro expands to C++11 noexcept, if available, or to nothing otherwise.

If you need the operator version of C++11 noexcept, use Q_DECL_NOEXCEPT_EXPR(x).

If you don’t need C++11 noexcept semantics, e.g. because your function can’t possibly throw, don’t use this macro, use Q_DECL_NOTHROW instead.

This function was introduced in Qt 5.0.

Q_DECL_NOEXCEPT_EXPR (x)

This macro marks a function as non-throwing if x is true . If the function does nevertheless throw, the behaviour is defined: std::terminate() is called.

The macro expands to C++11 noexcept(x), if available, or to nothing otherwise.

If you need the always-true version of C++11 noexcept, use Q_DECL_NOEXCEPT.

If you don’t need C++11 noexcept semantics, e.g. because your function can’t possibly throw, don’t use this macro, use Q_DECL_NOTHROW instead.

This function was introduced in Qt 5.0.

Q_DECL_NOTHROW

This macro marks a function as never throwing, under no circumstances. If the function does nevertheless throw, the behaviour is undefined.

The macro expands to either «throw()», if that has some benefit on the compiler, or to C++11 noexcept, if available, or to nothing otherwise.

If you need C++11 noexcept semantics, don’t use this macro, use Q_DECL_NOEXCEPT/Q_DECL_NOEXCEPT_EXPR instead.

This function was introduced in Qt 5.0.

Q_DECL_RELAXED_CONSTEXPR

This macro can be used to declare an inline function that can be computed at compile-time according to the relaxed rules from C++14.

It expands to «constexpr» if your compiler supports C++14 relaxed constant expressions, or to nothing otherwise.

void Q_FALLTHROUGH

Can be used in switch statements at the end of case block to tell the compiler and other developers that that the lack of a break statement is intentional.

This is useful since a missing break statement is often a bug, and some compilers can be configured to emit warnings when one is not found.

This function was introduced in Qt 5.8.

Q_FOREACH (variable, container)

Same as foreach(variable, container).

This macro is available even when no_keywords is specified using the .pro file’s CONFIG variable.

Note: Since Qt 5.7, the use of this macro is discouraged. It will be removed in a future version of Qt. Please use C++11 range-for, possibly with qAsConst(), as needed.

Q_FOREVER

This macro is available even when no_keywords is specified using the .pro file’s CONFIG variable.

Q_FORWARD_DECLARE_CF_TYPE (type)

Forward-declares a Core Foundation type. This includes the actual type and the ref type. For example, Q_FORWARD_DECLARE_CF_TYPE(CFString) declares __CFString and CFStringRef.

This function was introduced in Qt 5.2.

Q_FORWARD_DECLARE_MUTABLE_CF_TYPE (type)

Forward-declares a mutable Core Foundation type. This includes the actual type and the ref type. For example, Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(CFMutableString) declares __CFMutableString and CFMutableStringRef.

This function was introduced in Qt 5.2.

Q_FORWARD_DECLARE_OBJC_CLASS (classname)

Forward-declares an Objective-C classname in a manner such that it can be compiled as either Objective-C or C++.

This is primarily intended for use in header files that may be included by both Objective-C and C++ source files.

This function was introduced in Qt 5.2.

const char * Q_FUNC_INFO

Expands to a string that describe the function the macro resides in. How this string looks more specifically is compiler dependent. With GNU GCC it is typically the function signature, while with other compilers it might be the line and column number.

Q_FUNC_INFO can be conveniently used with qDebug(). For example, this function:

when instantiated with the integer type, will with the GCC compiler produce:

const TInputType& myMin(const TInputType&, const TInputType&) [with TInputType = int] was called with value1: 3 value2: 4

If this macro is used outside a function, the behavior is undefined.

qint64 Q_INT64_C (literal)

Wraps the signed 64-bit integer literal in a platform-independent way.

Q_LIKELY (expr)

Hints to the compiler that the enclosed condition, expr, is likely to evaluate to true .

Use of this macro can help the compiler to optimize the code.

This function was introduced in Qt 4.8.

Q_LITTLE_ENDIAN

This macro represents a value you can compare to the macro Q_BYTE_ORDER to determine the endian-ness of your system. In a little-endian system, the least significant byte is stored at the lowest address. The other bytes follow in increasing order of significance.

Источник

Читайте также:  Как называется процесс linux
Оцените статью