<QtGlobal> 头文件包括基础全局声明。它被包括在大多数其它 Qt 头文件中。
The global declarations include types, functions and macros.
类型定义是基本类型的部分方便定义 (其中一些保证 Qt 支持的所有平台的某些位尺寸),部分类型有关 Qt 消息处理。函数有关生成消息、Qt 版本处理及比较/调节对象值。最后,某些声明宏使程序员能够向其应用程序添加编译器或平台特定代码,而其它的是用于更大操作的方便宏。
类型 ¶
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
qint8which is a signed char guaranteed to be 8-bit on all platforms supported by Qt. The header file also declares theqlonglongtype definition forlong long int(__int64在 Windows)。Several convenience type definitions are declared:
qrealfordoubleorfloat,ucharforunsignedchar,uintforunsignedint,ulongforunsignedlong andushortforunsignedshort.Finally, the
QtMsgTypedefinition identifies the various messages that can be generated and sent to a Qt message handler;QtMessageHandleris a type definition for a pointer to a function with the signaturevoid myMessageHandler(QtMsgType, const QMessageLogContext &, const char *).QMessageLogContextclass contains the line, file, and function the message was logged at. This information is created by theQMessageLogger类。
函数 ¶
The <QtGlobal> 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 theqBound()function. You can retrieve the minimum and maximum of two given objects usingqMin()andqMax()respectively. All these functions return a corresponding template type; the template types can be replaced by any other type.范例:
int myValue = 10; int minValue = 2; int maxValue = 6; int boundedValue = qBound(minValue, myValue, maxValue); // boundedValue == 6<QtGlobal> also contains functions that generate messages from the given string argument:
qDebug(),qInfo(),qWarning(),qCritical(),和qFatal(). These functions call the message handler with the given message.范例:
if (!driver()->isOpen() || driver()->isOpenError()) { qWarning("QSqlQuery::exec: database not open"); return false; }The remaining functions are
qRound()andqRound64(), which both accept adoubleorfloatvalue as their argument returning the value rounded up to the nearest integer and 64-bit integer respectively, theqInstallMessageHandler()function which installs the givenQtMessageHandler,和qVersion()function which returns the version number of Qt at run-time as a string.
宏 ¶
<QtGlobal> 头文件提供一系列定义宏 (Q_CC_*) 若使用指定平台编译应用程序。例如,
Q_CC_SUN定义宏,若使用 Forte Developer 或 Sun Studio C++ 编译应用程序。头文件还为指定平台声明了一系列定义宏 (Q_OS_*)。例如,Q_OS_UNIX是为基于 Unix 的系统定义的。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(),和QT_TRANSLATE_NOOP3()macros provide the possibility of marking strings for delayed translation.QT_TR_N_NOOP(),QT_TRANSLATE_N_NOOP(),和QT_TRANSLATE_N_NOOP3()are numerator dependent variants of these. TheQ_ASSERT()andQ_ASSERT_X()enables warning messages of various level of refinement. TheQ_FOREACH()andforeach()macros implement Qt’s foreach loop.
Q_INT64_C()andQ_UINT64_C()macros wrap signed and unsigned 64-bit integer literals in a platform-independent way. TheQ_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 isNone。qPrintable()andqUtf8Printable()macros represent an easy way of printing text.
QT_POINTER_SIZEmacro expands to the size of a pointer in bytes.The macros
QT_VERSIONandQT_VERSION_STRexpand to a numeric value or a string, respectively, that specifies the version of Qt that the application is compiled against.另请参阅
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_BEFOREQT_NO_DEPRECATED_WARNINGSThis 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=0x050100to disable functions deprecated in Qt 5.1 and earlier. In any release, setQT_DISABLE_DEPRECATED_BEFORE=0x000000to enable all functions, including the ones deprecated in Qt 5.0.另请参阅
QT_DEPRECATED_WARNINGSThis macro can be used to suppress deprecation warnings that would otherwise be generated when using deprecated APIs.
另请参阅
QT_DISABLE_DEPRECATED_BEFOREExpands 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.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).
argcandargvparameters are themain()function’sargcandargvparameters. Theversionparameter is a string literal that specifies which version of Qt the application requires (e.g., “4.0.2”).范例:
#include <QApplication> #include <QMessageBox> int main(int argc, char *argv[]) { QT_REQUIRE_VERSION(argc, argv, "4.0.2") QApplication app(argc, argv); ... return app.exec(); }In general, use of the
Q_DECL_NOEXCEPTmacro is preferred overQ_DECL_NOTHROW, because it exhibits well-defined behavior and supports the more powerfulQ_DECL_NOEXCEPT_EXPRvariant. However, use ofQ_DECL_NOTHROWhas the advantage that Windows builds benefit on a wide range or compiler versions that do not yet support the C++11 noexcept feature.It may therefore be beneficial to use
Q_DECL_NOTHROWand emulate the C++11 behavior manually with an embedded try/catch.Qt provides the QT_TERMINATE_ON_EXCEPTION(expr) macro for this purpose. It either expands to
expr(if Qt is compiled without exception support or the compiler supports C++11 noexcept semantics) or totry { expr; } catch(...) { qTerminate(); }否则。
Since this macro expands to just
exprif the compiler supports C++11 noexcept, expecting the compiler to take over responsibility of calling std::terminate() in that case, it should not be used outsideQ_DECL_NOTHROW函数。另请参阅
Q_DECL_NOEXCEPTQ_DECL_NOTHROWqTerminate()Marks the UTF-8 encoded string literal
sourceTextfor delayed translation in the givencontext。contextis 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本身。范例:
static const char *greeting_strings[] = { QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type]); } QString global_greeting(int type) { return qApp->translate("FriendlyConversation", greeting_strings[type]); }另请参阅
QT_TR_NOOP()QT_TRANSLATE_NOOP3()国际化 with QtMarks the UTF-8 encoded string literal
sourceTextfor delayed translation in the givencontext采用给定disambiguation。contextis typically a class and also needs to be specified as a string literal. The string literaldisambiguationshould 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
sourceTextanddisambiguation.范例:
static { const char *source; const char *comment; } greeting_strings[] = { QT_TRANSLATE_NOOP3("FriendlyConversation", "Hello", "A really friendly hello"), QT_TRANSLATE_NOOP3("FriendlyConversation", "Goodbye", "A really friendly goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type].source, greeting_strings[type].comment); } QString global_greeting(int type) { return qApp->translate("FriendlyConversation", greeting_strings[type].source, greeting_strings[type].comment); }另请参阅
QT_TR_NOOP()QT_TRANSLATE_NOOP()国际化 with QtMarks the UTF-8 encoded string literal
sourceTextfor numerator dependent delayed translation in the givencontext。contextis 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本身。范例:
static const char * const greeting_strings[] = { QT_TRANSLATE_N_NOOP("Welcome Msg", "Hello, you have %n message(s)"), QT_TRANSLATE_N_NOOP("Welcome Msg", "Hi, you have %n message(s)") }; QString global_greeting(int type, int msgcnt) { return translate("Welcome Msg", greeting_strings[type], nullptr, msgcnt); }另请参阅
QT_TRANSLATE_NOOP()QT_TRANSLATE_N_NOOP3()国际化 with QtMarks the UTF-8 encoded string literal
sourceTextfor numerator dependent delayed translation in the givencontext采用给定comment。contextis typically a class and also needs to be specified as a string literal. The string literalcommentshould 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
sourceTextandcomment.范例:
static { const char * const source; const char * const comment; } status_strings[] = { QT_TRANSLATE_N_NOOP3("Message Status", "Hello, you have %n message(s)", "A login message status"), QT_TRANSLATE_N_NOOP3("Message status", "You have %n new message(s)", "A new message query status") }; QString FriendlyConversation::greeting(int type, int count) { return tr(status_strings[type].source, status_strings[type].comment, count); } QString global_greeting(int type, int count) { return qApp->translate("Message Status", status_strings[type].source, status_strings[type].comment, count); }另请参阅
QT_TR_NOOP()QT_TRANSLATE_NOOP()QT_TRANSLATE_NOOP3()国际化 with QtThe 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.范例:
static const char * const ids[] = { //% "This is the first text." QT_TRID_NOOP("qtn_1st_text"), //% "This is the second text." QT_TRID_NOOP("qtn_2nd_text"), 0 }; void TheClass::addLabels() { for (int i = 0; ids[i]; ++i) new QLabel(qtTrId(ids[i]), this); }另请参阅
qtTrId()国际化 with QtMarks the UTF-8 encoded string literal
sourceTextfor delayed translation in the current context (class).The macro tells lupdate to collect the string, and expands to
sourceText本身。范例:
QString FriendlyConversation::greeting(int type) { static const char *greeting_strings[] = { QT_TR_NOOP("Hello"), QT_TR_NOOP("Goodbye") }; return tr(greeting_strings[type]); }The macro QT_TR_NOOP_UTF8() is identical and obsolete; this applies to all other _UTF8 macros as well.
另请参阅
QT_TRANSLATE_NOOP()国际化 with QtMarks the UTF-8 encoded string literal
sourceTextfor numerator dependent delayed translation in the current context (class).The macro tells lupdate to collect the string, and expands to
sourceText本身。The macro expands to
sourceText.范例:
static const char * const StatusClass::status_strings[] = { QT_TR_N_NOOP("There are %n new message(s)"), QT_TR_N_NOOP("There are %n total message(s)") }; QString StatusClass::status(int type, int count) { return tr(status_strings[type], nullptr, count); }另请参阅
QT_TR_NOOP国际化 with QtThis 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 macro will expand to 0x040102.
You can use to use the latest Qt features where available.
范例:
#if QT_VERSION >= 0x040100 QIcon icon = style()->standardIcon(QStyle::SP_TrashIcon); #else QPixmap pixmap = style()->standardPixmap(QStyle::SP_TrashIcon); QIcon icon(pixmap); #endif另请参阅
QT_VERSION_STRqVersion()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.
范例:
#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif另请参阅
QT_VERSIONThis 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.
另请参阅
qVersion()QT_VERSIONPrints a warning message containing the source code file name and line number if
testisfalse.is useful for testing pre- and post-conditions during development. It does nothing if
QT_NO_DEBUGwas defined during compilation.范例:
// File: div.cpp #include <QtGlobal> int divide(int a, int b) { Q_ASSERT(b != 0); return a / b; }若
bis zero, the statement will output the following message using theqFatal()函数:ASSERT: "b != 0" in file div.cpp, line 7另请参阅
Q_ASSERT_X()qFatal()调试 TechniquesPrints the message
whattogether with the locationwhere, the source file name and line number iftestisfalse.is useful for testing pre- and post-conditions during development. It does nothing if
QT_NO_DEBUGwas defined during compilation.范例:
// File: div.cpp #include <QtGlobal> int divide(int a, int b) { Q_ASSERT_X(b != 0, "divide", "division by zero"); return a / b; }若
bis zero, the statement will output the following message using theqFatal()函数:ASSERT failure in divide: "division by zero", file div.cpp, line 7另请参阅
Q_ASSERT()qFatal()调试 TechniquesCauses the compiler to assume that
expristrue. 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(). WhileQ_ASSERTwill abort the program’s execution if the condition isfalse, 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.若
expris a constantlyfalsecondition, will tell the compiler that the current code execution cannot be reached. That is, (false) is equivalent toQ_UNREACHABLE().In debug builds the condition is enforced by an assert to facilitate debugging.
注意
Q_LIKELY()tells the compiler that the expression is likely, but not the only possibility. tells the compiler that it is the only possibility.另请参阅
Q_ASSERT()Q_UNREACHABLE()Q_LIKELY()This macro represents a value you can compare to the macro
Q_BYTE_ORDERto 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.#if Q_BYTE_ORDER == Q_BIG_ENDIAN ... #endif另请参阅
Q_BYTE_ORDERQ_LITTLE_ENDIANThis 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_ENDIANorQ_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 must pass data back and forth.Use this macro as in the following examples.
#if Q_BYTE_ORDER == Q_BIG_ENDIAN ... #endif or #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN ... #endif另请参阅
Q_BIG_ENDIANQ_LITTLE_ENDIANDefined if the application is compiled using Borland/Turbo C++.
Defined if the application is compiled using Reliant C++.
Defined if the application is compiled using Clang.
Defined if the application is compiled using Comeau C++.
Defined if the application is compiled using DEC C++.
Defined if the application is compiled using Edison Design Group C++.
Defined if the application is compiled using Green Hills Optimizing C++ Compilers.
Defined if the application is compiled using GNU C++.
Defined if the application is compiled using MetaWare High C/C++.
Defined if the application is compiled using HP aC++.
Defined if the application is compiled using Intel C++ for Linux, Intel C++ for Windows.
Defined if the application is compiled using KAI C++.
Defined if the application is compiled using MIPSpro C++.
Defined if the application is compiled using Microsoft Visual C/C++, Intel C++ for Windows.
Defined if the application is compiled using CenterLine C++.
Defined if the application is compiled using Portland Group C++.
Defined if the application is compiled using Forte Developer, or Sun Studio C++.
Defined if the application is compiled using Digital Mars C/C++ (used to be Symantec C++).
Defined if the application is compiled using SCO OUDK and UDK.
Defined if the application is compiled using Watcom C++.
若
pointerisNone, 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 throwsstd::bad_allocinstead if exceptions are enabled.does nothing if
QT_NO_DEBUGandQT_NO_EXCEPTIONSwere defined during compilation. Therefore you must not use to check for successful memory allocations because the check will be disabled in some cases.范例:
int *a; Q_CHECK_PTR(a = new int[80]); // WRONG! a = new (nothrow) int[80]; // Right Q_CHECK_PTR(a);另请参阅
qWarning()调试 TechniquesYou 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.
标志can be one of the following:
Q_PRIMITIVE_TYPEspecifies thatTypeis a POD (plain old data) type with no constructor or destructor, or else a type where every bit pattern is a valid object and memcpy() creates a valid independent copy of the object.
Q_MOVABLE_TYPEspecifies thatTypehas a constructor and/or a destructor but can be moved in memory usingmemcpy(). Note: despite the name, this has nothing to do with move constructors or C++ move semantics.
Q_COMPLEX_TYPE(the default) specifies thatTypehas constructors and/or a destructor and that it may not be moved in memory.Example of a “primitive” type:
struct Point2D { int x; int y; }; Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_TYPE);An example of a non-POD “primitive” type is
QUuid: Even thoughQUuidhas 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 aQUuid对象。Example of a movable type:
class Point2D { public: Point2D() { data = new int[2]; } Point2D(const Point2D &other) { ... } ~Point2D() { delete[] data; } Point2D &operator=(const Point2D &other) { ... } int x() const { return data[0]; } int y() const { return data[1]; } private: int *data; }; Q_DECLARE_TYPEINFO(Point2D, Q_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 despite not being trivially-copyable. For binary compatibility reasons,
QListoptimizations are only enabled if there is an explicit even for trivially-copyable types.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_RELAXED_CONSTEXPRThis macro marks a symbol for shared library export (see Creating Shared Libraries).
另请参阅
Q_DECL_IMPORTThis macro can be used to declare an overriding virtual or a class as “final”, with Java semantics. Further-derived classes can then no longer override this virtual function, or inherit from this class, respectively.
It expands to “final”.
The macro goes at the end of the function, usually after the
const, if any:// more-derived classes no longer permitted to override this: virtual void MyWidget::paintEvent(QPaintEvent*) final;For classes, it goes in front of the
:in the class definition, if any:class QRect final { // cannot be derived from // ... };另请参阅
Q_DECL_OVERRIDEThis macro declares a symbol to be an import from a shared library (see Creating Shared Libraries).
另请参阅
Q_DECL_EXPORTThis 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代替。另请参阅
Q_DECL_NOTHROWQ_DECL_NOEXCEPT_EXPR()This macro marks a function as non-throwing if
xistrue. 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代替。另请参阅
Q_DECL_NOTHROWQ_DECL_NOEXCEPTThis 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代替。另请参阅
Q_DECL_NOEXCEPTQ_DECL_NOEXCEPT_EXPR()This macro can be used to declare an overriding virtual function. Use of this markup will allow the compiler to generate an error if the overriding virtual function does not in fact override anything.
It expands to “override”.
The macro goes at the end of the function, usually after the
const, if any:// generate error if this doesn't actually override anything: virtual void MyWidget::paintEvent(QPaintEvent*) override;另请参阅
Q_DECL_FINALThis 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.
另请参阅
Q_DECL_CONSTEXPRCan 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.
另请参阅
Q_UNREACHABLE()Same as foreach(
variable,container).This macro is available even when
no_keywordsis specified using the.profile’sCONFIG变量。注意
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.另请参阅
qAsConst()如同
forever.This macro is available even when
no_keywordsis specified using the.profile’sCONFIG变量。另请参阅
foreach()Forward-declares a Core Foundation
type. This includes the actual type and the ref type. For example, (CFString) declares __CFString and CFStringRef.Forward-declares a mutable Core Foundation
type. This includes the actual type and the ref type. For example, (CFMutableString) declares __CFMutableString and CFMutableStringRef.Forward-declares an Objective-C
classnamein 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.
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.
can be conveniently used with
qDebug(). For example, this function:template<typename TInputType> const TInputType &myMin(const TInputType &value1, const TInputType &value2) { qDebug() << Q_FUNC_INFO << "was called with value1:" << value1 << "value2:" << value2; if(value1 < value2) return value1; else return value2; }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: 4If this macro is used outside a function, the behavior is undefined.
Wraps the signed 64-bit integer
literalin a platform-independent way.范例:
qint64 value = Q_INT64_C(932838457459459);另请参阅
qint64Q_UINT64_C()Hints to the compiler that the enclosed condition,
expr, is likely to evaluate totrue.Use of this macro can help the compiler to optimize the code.
范例:
// the condition inside the "if" will be successful most of the times for (int i = 1; i <= 365; i++) { if (Q_LIKELY(isWorkingDay(i))) { ... } ... }另请参阅
Q_UNLIKELY()This macro represents a value you can compare to the macro
Q_BYTE_ORDERto 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.#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN ... #endif另请参阅
Q_BYTE_ORDERQ_BIG_ENDIANDefined on AIX.
Defined on Android.
Defined on Any BSD 4.4 system.
Defined on Cygwin.
Defined on Darwin-based operating systems such as macOS, iOS, watchOS, and tvOS.
Defined on FreeBSD.
Defined on HP-UX.
Defined on GNU Hurd.
Defined on iOS.
Defined on Linux.
Defined on LynxOS.
Deprecated synonym for
Q_OS_DARWIN. Do not use.Defined on macOS.
Defined on NetBSD.
Defined on OpenBSD.
Deprecated synonym for
Q_OS_MACOS. Do not use.Defined on QNX Neutrino.
Defined on Sun Solaris.
Defined on tvOS.
Defined on Any UNIX BSD/SYSV system.
Defined on Web Assembly.
Defined on watchOS.
Defined on all supported versions of Windows. That is, if
Q_OS_WIN32,Q_OS_WIN64,或Q_OS_WINRTis defined.Defined on 32-bit and 64-bit versions of Windows.
Defined on 64-bit versions of Windows.
This is a synonym for
Q_OS_WIN.Defined for Windows Runtime (Windows Store apps) on Windows 8, Windows RT, and Windows Phone 8.
Defined if the application is compiled for Alpha processors.
另请参阅
buildCpuArchitecture()Defined if the application is compiled for ARM processors. Qt currently supports three optional ARM revisions:
Q_PROCESSOR_ARM_V5,Q_PROCESSOR_ARM_V6,和Q_PROCESSOR_ARM_V7.另请参阅
buildCpuArchitecture()Defined if the application is compiled for ARMv5 processors. The
Q_PROCESSOR_ARMmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for ARMv6 processors. The
Q_PROCESSOR_ARMandQ_PROCESSOR_ARM_V5macros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for ARMv7 processors. The
Q_PROCESSOR_ARM,Q_PROCESSOR_ARM_V5,和Q_PROCESSOR_ARM_V6macros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for AVR32 processors.
另请参阅
buildCpuArchitecture()Defined if the application is compiled for Blackfin processors.
另请参阅
buildCpuArchitecture()Defined if the application is compiled for IA-64 processors. This includes all Itanium and Itanium 2 processors.
另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS processors. Qt currently supports seven MIPS revisions:
Q_PROCESSOR_MIPS_I,Q_PROCESSOR_MIPS_II,Q_PROCESSOR_MIPS_III,Q_PROCESSOR_MIPS_IV,Q_PROCESSOR_MIPS_V,Q_PROCESSOR_MIPS_32,和Q_PROCESSOR_MIPS_64.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS32 processors. The
Q_PROCESSOR_MIPS,Q_PROCESSOR_MIPS_I,和Q_PROCESSOR_MIPS_IImacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS64 processors. The
Q_PROCESSOR_MIPS,Q_PROCESSOR_MIPS_I,Q_PROCESSOR_MIPS_II,Q_PROCESSOR_MIPS_III,Q_PROCESSOR_MIPS_IV,和Q_PROCESSOR_MIPS_Vmacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS-I processors. The
Q_PROCESSOR_MIPSmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS-II processors. The
Q_PROCESSOR_MIPSandQ_PROCESSOR_MIPS_Imacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS-III processors. The
Q_PROCESSOR_MIPS,Q_PROCESSOR_MIPS_I,和Q_PROCESSOR_MIPS_IImacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS-IV processors. The
Q_PROCESSOR_MIPS,Q_PROCESSOR_MIPS_I,Q_PROCESSOR_MIPS_II,和Q_PROCESSOR_MIPS_IIImacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for MIPS-V processors. The
Q_PROCESSOR_MIPS,Q_PROCESSOR_MIPS_I,Q_PROCESSOR_MIPS_II,Q_PROCESSOR_MIPS_III,和Q_PROCESSOR_MIPS_IVmacros are also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for POWER processors. Qt currently supports two Power variants:
Q_PROCESSOR_POWER_32andQ_PROCESSOR_POWER_64.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 32-bit Power processors. The
Q_PROCESSOR_POWERmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 64-bit Power processors. The
Q_PROCESSOR_POWERmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for RISC-V processors. Qt currently supports two RISC-V variants:
Q_PROCESSOR_RISCV_32andQ_PROCESSOR_RISCV_64.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 32-bit RISC-V processors. The
Q_PROCESSOR_RISCVmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 64-bit RISC-V processors. The
Q_PROCESSOR_RISCVmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for S/390 processors. Qt supports one optional variant of S/390:
Q_PROCESSOR_S390_X.另请参阅
buildCpuArchitecture()Defined if the application is compiled for S/390x processors. The
Q_PROCESSOR_S390macro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for SuperH processors. Qt currently supports one SuperH revision:
Q_PROCESSOR_SH_4A.另请参阅
buildCpuArchitecture()Defined if the application is compiled for SuperH 4A processors. The
Q_PROCESSOR_SHmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for SPARC processors. Qt currently supports one optional SPARC revision:
Q_PROCESSOR_SPARC_V9.另请参阅
buildCpuArchitecture()Defined if the application is compiled for SPARC V9 processors. The
Q_PROCESSOR_SPARCmacro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for x86 processors. Qt currently supports two x86 variants:
Q_PROCESSOR_X86_32andQ_PROCESSOR_X86_64.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 32-bit x86 processors. This includes all i386, i486, i586, and i686 processors. The
Q_PROCESSOR_X86macro is also defined when is defined.另请参阅
buildCpuArchitecture()Defined if the application is compiled for 64-bit x86 processors. This includes all AMD64, Intel 64, and other x86_64/x64 processors. The
Q_PROCESSOR_X86macro is also defined when is defined.另请参阅
buildCpuArchitecture()Wraps the unsigned 64-bit integer
literalin a platform-independent way.范例:
quint64 value = Q_UINT64_C(932838457459459);另请参阅
quint64Q_INT64_C()Hints to the compiler that the enclosed condition,
expr, is likely to evaluate tofalse.Use of this macro can help the compiler to optimize the code.
范例:
bool readConfiguration(const QFile &file) { // We expect to be asked to read an existing file if (Q_UNLIKELY(!file.exists())) { qWarning() << "File not found"; return false; } ... return true; }另请参阅
Q_LIKELY()Tells the compiler that the current point cannot be reached by any execution, so it may optimize any code paths leading here as dead code, as well as code continuing from here.
This macro is useful to mark impossible conditions. For example, given the following enum:
enum Shapes { Rectangle, Triangle, Circle, NumShapes };One can write a switch table like so:
switch (shape) { case Rectangle: return rectangle(); case Triangle: return triangle(); case Circle: return circle(); case NumShapes: Q_UNREACHABLE(); break; }The advantage of inserting at that point is that the compiler is told not to generate code for a shape variable containing that value. If the macro is missing, the compiler will still generate the necessary comparisons for that value. If the case label were removed, some compilers could produce a warning that some enum values were not checked.
By using this macro in impossible conditions, code coverage may be improved as dead code paths may be eliminated.
In debug builds the condition is enforced by an assert to facilitate debugging.
另请参阅
Q_ASSERT()Q_ASSUME()qFatal()Indicates to the compiler that the parameter with the specified
nameis not used in the body of a function. This can be used to suppress compiler warnings while allowing functions to be defined with meaningful parameter names in their signatures.This macro is used to implement Qt’s
foreachloop. Thevariableparameter is a variable name or variable definition; thecontainerparameter is a Qt container whose value type corresponds to the type of the variable. See foreach 关键字 了解细节。If you’re worried about namespace pollution, you can disable this macro by adding the following line to your
.pro文件:CONFIG += no_keywords注意
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.另请参阅
qAsConst()This macro is provided for convenience for writing infinite loops.
范例:
forever { ... }它相当于
for (;;).If you’re worried about namespace pollution, you can disable this macro by adding the following line to your
.pro文件:CONFIG += no_keywords另请参阅
Q_FOREVER比较
tto the 0 of type T and returns the absolute value. Thus if T is double ,那么tis compared to (double) 0 .范例:
int absoluteValue; int myValue = -4; absoluteValue = qAbs(myValue); // absoluteValue == 4返回
tcast toconst 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:
QString s = ...; for (QChar ch : s) // detaches 's' (performs a deep-copy if 's' was shared) process(ch); for (QChar ch : qAsConst(s)) // ok, no detach attempt process(ch);Of course, in this case, you could (and probably should) have declared
sasconstin the first place:const QString s = ...; for (QChar ch : s) // ok, no detach attempt on const objects process(ch);but often that is not easily possible.
It is important to note that does not copy its argument, it just performs a
const_cast<const T&>(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):for (QChar ch : funcReturningQString()) process(ch); // OK, the returned object is kept alive for the loop's durationthis would not:
for (QChar ch : qAsConst(funcReturningQString())) process(ch); // ERROR: ch is copied from deleted memoryTo prevent this construct from compiling (and failing at runtime), has a second, deleted, overload which binds to rvalues.
这是重载函数。
This overload is deleted to prevent a dangling reference in code like
for (QChar ch : qAsConst(funcReturningQString())) process(ch); // ERROR: ch is copied from deleted memory返回
valbounded byminandmax。这相当于qMax(min,qMin(val,max)).范例:
int myValue = 10; int minValue = 2; int maxValue = 6; int boundedValue = qBound(minValue, myValue, maxValue); // boundedValue == 6另请参阅
qMin()qMax()返回
memberFunctionPointerpointer to a constant member function:struct Foo { void overloadedFunction(int, const QString &); void overloadedFunction(int, const QString &) const; }; ... qConstOverload<int, const QString &>(&Foo::overloadedFunction) ... qNonConstOverload<int, const QString &>(&Foo::overloadedFunction)另请参阅
qOverloadqNonConstOverloadDifferences between String-Based and Functor-Based ConnectionsCalls the message handler with the critical message
message. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2.It exits if the environment variable QT_FATAL_CRITICALS is not empty.
This function takes a format string and a list of arguments, similar to the C printf() function. The format should be a Latin-1 string.
范例:
void load(const QString &fileName) { QFile file(fileName); if (!file.exists()) qCritical("File '%s' does not exist!", qUtf8Printable(fileName)); }If you include <QtDebug>, a more convenient syntax is also available:
qCritical() << "Brush:" << myQBrush << "Other value:" << i;A space is inserted between the items, and a newline is appended at the end.
To suppress the output at runtime, install your own message handler with
qInstallMessageHandler().另请参阅
qDebug()qInfo()qWarning()qFatal()qInstallMessageHandler()调试 TechniquesCalls the message handler with the debug message
message. If no message handler has been installed, the message is printed to stderr. Under Windows the message is sent to the console, if it is a console application; otherwise, it is sent to the debugger. On QNX, the message is sent to slogger2. This function does nothing ifQT_NO_DEBUG_OUTPUTwas defined during compilation.If you pass the function a format string and a list of arguments, it works in similar way to the C printf() function. The format should be a Latin-1 string.
范例:
qDebug("Items in list: %d", myList.size());If you include
<QtDebug>, a more convenient syntax is also available:qDebug() << "Brush:" << myQBrush << "Other value:" << i;With this syntax, the function returns a
QDebugobject that is configured to use theQtDebugMsgmessage type. It automatically puts a single space between each item, and outputs a newline at the end. It supports many C++ and Qt types.To suppress the output at run-time, install your own message handler with
qInstallMessageHandler().另请参阅
qInfo()qWarning()qCritical()qFatal()qInstallMessageHandler()调试 TechniquesReturns the numerical value of the environment variable
varName。若okis not null, sets*oktotrueorfalsedepending on the success of the conversion.相当于
qgetenv(varName).toInt(ok, 0)except that it’s much faster, and can’t throw exceptions.
注意
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
oktofalse.另请参阅
qgetenv()qEnvironmentVariable()qEnvironmentVariableIsSet()Returns whether the environment variable
varNameis empty.相当于
qgetenv(varName).isEmpty()except that it’s potentially much faster, and can’t throw exceptions.
另请参阅
qgetenv()qEnvironmentVariable()qEnvironmentVariableIsSet()Returns whether the environment variable
varName被设置。相当于
!qgetenv(varName).isNull()except that it’s potentially much faster, and can’t throw exceptions.
另请参阅
qgetenv()qEnvironmentVariable()qEnvironmentVariableIsEmpty()Replaces the value of
objwithnewValueand returns the old value ofobj.This is Qt’s implementation of std::exchange(). It differs from std::exchange() only in that it is
constexpralready in C++14, and available on all supported compilers.Here is how to use to implement move constructors:
MyClass(MyClass &&other) : m_pointer{qExchange(other.m_pointer, nullptr)}, m_int{qExchange(other.m_int, 0)}, m_vector{std::move(other.m_vector)}, ...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()/ 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 to write a loop that consumes the collection it iterates over:
for (auto &e : qExchange(collection, {}) doSomethingWith(e);Which is equivalent to the following, much more verbose code:
{ auto tmp = std::move(collection); collection = {}; // or collection.clear() for (auto &e : tmp) doSomethingWith(e); } // destroys 'tmp'This is perfectly safe, as the for-loop keeps the result of alive for as long as the loop runs, saving the declaration of a temporary variable. Be aware, though, that returns a non-const object, so Qt containers may detach.
Calls the message handler with the fatal message
message. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2.If you are using the default message handler this function will abort to create a core dump. On Windows, for debug builds, this function will report a _CRT_ERROR enabling you to connect a debugger to the application.
This function takes a format string and a list of arguments, similar to the C printf() function.
范例:
int divide(int a, int b) { if (b == 0) // program error qFatal("divide: cannot divide by zero"); return a / b; }To suppress the output at runtime, install your own message handler with
qInstallMessageHandler().另请参阅
qDebug()qInfo()qWarning()qCritical()qInstallMessageHandler()调试 TechniquesReturns the number of representable floating-point numbers between
aandb.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
aandbare 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_MAXand+FLT_MAX.The function does not give meaningful results if any of the arguments are
InfiniteorNaN. You can check for this by callingqIsFinite().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:
if (qFloatDistance(a, b) < (1 << 7)) { // The last 7 bits are not // significant // precise enough }另请参阅
qFuzzyCompare()Returns the number of representable floating-point numbers between
aandb.This function serves the same purpose as
qFloatDistance(float, float), but returns the distance between twodoublenumbers. Since the range is larger than for twofloatnumbers ([-DBL_MAX,DBL_MAX]), the return type is quint64.另请参阅
qFuzzyCompare()Generates a formatted string out of the
type,context,str自变量。返回
QStringthat 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.
另请参阅
qInstallMessageHandler()qSetMessagePattern()分类浮点值。
返回值的定义在
<cmath>: returns one of the following, determined by the floating-point class ofval:
FP_NAN 非数字
FP_INFINITE 无穷大 (正值或负值)
FP_ZERO zero (positive or negative)
FP_NORMAL finite with a full mantissa
FP_SUBNORMAL finite with a reduced mantissa
这是重载函数。
比较浮点值
p1andp2并返回true若它们被认为相等,否则false.Note that comparing values where either
p1orp2is 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, useqFuzzyIsNullinstead. If one of the values is likely to be 0.0, one solution is to add 1.0 to both values.// Instead of comparing with 0.0 qFuzzyCompare(0.0, 1.0e-200); // This will return false // Compare adding 1 to both values will fix the problem qFuzzyCompare(1 + 0.0, 1 + 1.0e-200); // This will return trueThe two numbers are compared in a relative way, where the exactness is stronger the smaller the numbers are.
比较浮点值
p1andp2并返回true若它们被认为相等,否则false.The two numbers are compared in a relative way, where the exactness is stronger the smaller the numbers are.
比较浮点值
p1andp2并返回true若它们被认为相等,否则false.The two numbers are compared in a relative way, where the exactness is stronger the smaller the numbers are.
Returns true if the absolute value of
dis within 0.000000000001 of 0.0.Returns true if the absolute value of
fis within 0.00001f of 0.0.Returns the bit pattern for an infinite number as a double.
另请参阅
qIsInf()Calls the message handler with the informational message
message. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the console, if it is a console application; otherwise, it is sent to the debugger. On QNX the message is sent to slogger2. This function does nothing ifQT_NO_INFO_OUTPUTwas defined during compilation.If you pass the function a format string and a list of arguments, it works in similar way to the C printf() function. The format should be a Latin-1 string.
范例:
qInfo("Items in list: %d", myList.size());If you include
<QtDebug>, a more convenient syntax is also available:qInfo() << "Brush:" << myQBrush << "Other value:" << i;With this syntax, the function returns a
QDebugobject that is configured to use theQtInfoMsgmessage type. It automatically puts a single space between each item, and outputs a newline at the end. It supports many C++ and Qt types.To suppress the output at run-time, install your own message handler with
qInstallMessageHandler().另请参阅
qDebug()qWarning()qCritical()qFatal()qInstallMessageHandler()调试 TechniquesInstalls a Qt message
handlerwhich 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).范例:
#include <qapplication.h> #include <stdio.h> #include <stdlib.h> void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); const char *file = context.file ? context.file : ""; const char *function = context.function ? context.function : ""; switch (type) { case QtDebugMsg: fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); break; case QtInfoMsg: fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); break; case QtWarningMsg: fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); break; case QtCriticalMsg: fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); break; case QtFatalMsg: fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function); break; } } int main(int argc, char **argv) { qInstallMessageHandler(myMessageOutput); QApplication app(argc, argv); ... return app.exec(); }另请参阅
QtMessageHandlerQtMsgTypeqDebug()qInfo()qWarning()qCritical()qFatal()调试 TechniquesInstalls a Qt message
handlerwhich has been defined previously. This method is deprecated, useqInstallMessageHandler代替。另请参阅
QtMsgHandlerqInstallMessageHandler()返回
trueif the doubled是有限数。返回
trueif the floatf是有限数。返回 true 若
qfloat16f是有限数。另请参阅
qIsFinite返回
trueif the doubled相当于无穷大。另请参阅
qInf()返回
trueif the floatf相当于无穷大。另请参阅
qInf()返回 true 若
qfloat16f相当于无穷大。另请参阅
qIsInf返回
trueif the doubled是 NaN (非数字)。返回
trueif the floatf是 NaN (非数字)。返回 true 若
qfloat16f是 NaN (非数字)。另请参阅
qIsNaNReturns the maximum of
aandb.范例:
int myValue = 6; int yourValue = 4; int maxValue = qMax(myValue, yourValue); // maxValue == myValue另请参阅
qMin()qBound()Returns the minimum of
aandb.范例:
int myValue = 6; int yourValue = 4; int minValue = qMin(myValue, yourValue); // minValue == yourValue另请参阅
qMax()qBound()使用
std::move代替。It expands to “std::move”.
takes an rvalue reference to its parameter
x, and converts it to an xvalue.返回
memberFunctionPointer指针指向非常量成员函数:struct Foo { void overloadedFunction(int, const QString &); void overloadedFunction(int, const QString &) const; }; ... qConstOverload<int, const QString &>(&Foo::overloadedFunction) ... qNonConstOverload<int, const QString &>(&Foo::overloadedFunction)另请参阅
qOverloadqNonConstOverloadDifferences between String-Based and Functor-Based Connections返回重载函数指针。 模板参数是函数的自变量类型列表。
functionPointer是指针指向 (成员) 函数:struct Foo { void overloadedFunction(); void overloadedFunction(int, const QString &); }; ... qOverload<>(&Foo::overloadedFunction) ... qOverload<int, const QString &>(&Foo::overloadedFunction)若成员函数也是重载常量
qConstOverloadandqNonConstOverload需要用到。requires C++14 enabled. In C++11-only code, the helper classes QOverload, QConstOverload, and QNonConstOverload can be used directly:
... QOverload<>::of(&Foo::overloadedFunction) ... QOverload<int, const QString &>::of(&Foo::overloadedFunction)注意
Qt 检测必要 C++ 14 编译器支持,通过特征测试推荐从 C++ Committee’s Standing Document 6 .
另请参阅
qConstOverload()qNonConstOverload()Differences between String-Based and Functor-Based Connections返回
str作为const char *。这相当于str.toLocal8Bit().constData().The char pointer will be invalid after the statement in which is used. This is because the array returned by
toLocal8Bit()will fall out of scope.注意
qDebug(),qInfo(),qWarning(),qCritical(),qFatal()expect %s arguments to be UTF-8 encoded, while converts to local 8-bit encoding. ThereforeqUtf8Printable()should be used for logging strings instead of .另请参阅
qUtf8Printable()Returns the bit pattern of a quiet NaN as a double.
另请参阅
qIsNaN()圆整
d到最近整数。Rounds half up (e.g. 0.5 -> 1, -0.5 -> 0).
范例:
double valueA = 2.3; double valueB = 2.7; int roundedValueA = qRound(valueA); // roundedValueA = 2 int roundedValueB = qRound(valueB); // roundedValueB = 3圆整
d到最近整数。Rounds half up (e.g. 0.5f -> 1, -0.5f -> 0).
范例:
float valueA = 2.3; float valueB = 2.7; int roundedValueA = qRound(valueA); // roundedValueA = 2 int roundedValueB = qRound(valueB); // roundedValueB = 3圆整
value到最近整数。另请参阅
qRound圆整
d到最近 64 位整数。Rounds half up (e.g. 0.5 -> 1, -0.5 -> 0).
范例:
double valueA = 42949672960.3; double valueB = 42949672960.7; qint64 roundedValueA = qRound64(valueA); // roundedValueA = 42949672960 qint64 roundedValueB = qRound64(valueB); // roundedValueB = 42949672961圆整
d到最近 64 位整数。Rounds half up (e.g. 0.5f -> 1, -0.5f -> 0).
范例:
float valueA = 42949672960.3; float valueB = 42949672960.7; qint64 roundedValueA = qRound64(valueA); // roundedValueA = 42949672960 qint64 roundedValueB = qRound64(valueB); // roundedValueB = 42949672961圆整
value到最近 64 位整数。另请参阅
qRound64Returns the bit pattern of a signalling NaN as a double.
Changes the output of the default message handler.
Allows to tweak the output of
qDebug(),qInfo(),qWarning(),qCritical(),和qFatal(). The category logging output ofqCDebug(),qCInfo(),qCWarning(),和qCCritical()is formatted, too.Following placeholders are supported:
Placeholder
描述
%{appname}
applicationName()
%{category}Logging category
%{file}Path to source file
%{function}函数
%{line}Line in source file
%{message}The actual message
%{pid}
applicationPid()
%{threadid}The system-wide ID of current thread (if it can be obtained)
%{qthreadptr}A pointer to the current
QThread(result ofcurrentThread())
%{type}“debug”, “warning”, “critical” or “fatal”
%{time process}time of the message, in seconds since the process started (the token “process” is literal)
%{time boot}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
msecsSinceReference()).
%{time [format]}system time when the message occurred, formatted by passing the
formattotoString(). If the format is not specified, the format ofISODate被使用。
%{backtrace [depth=N] [separator="..."]}A backtrace with the number of frames specified by the optional
depthparameter (defaults to 5), and separated by the optionalseparatorparameter (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, useQMAKE_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
%{if-debug},%{if-info}%{if-warning},%{if-critical}or%{if-fatal}followed by an%{endif}. What is inside the%{if-*}and%{endif}will only be printed if the type matches.Finally, text inside
%{if-category}…%{endif}is only printed if the category is not the default one.范例:
QT_MESSAGE_PATTERN="[%{time yyyyMMdd h:mm:ss.zzz t} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}"默认
patternis “%{if-category}%{category}: %{endif}%{message}”.
patterncan 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.注意
The message pattern only applies to unstructured logging, such as the default
stderroutput. 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 takepatterninto account.另请参阅
qInstallMessageHandler()QLoggingCategory返回
str作为const ushort *, but cast to aconst wchar_t *to avoid warnings. This is equivalent tostr.utf16() plus some casting.The only useful thing you can do with the return value of this macro is to pass it to
asprintf()for use in a%lsconversion. In particular, the return value is not a validconst wchar_t*!In general, the pointer will be invalid after the statement in which is used. This is because the pointer may have been obtained from a temporary expression, which will fall out of scope.
范例:
qWarning("%ls: %ls", qUtf16Printable(key), qUtf16Printable(value));另请参阅
qPrintable()qDebug()qInfo()qWarning()qCritical()qFatal()返回
str作为const char *。这相当于str.toUtf8().constData().The char pointer will be invalid after the statement in which is used. This is because the array returned by
toUtf8()will fall out of scope.范例:
qWarning("%s: %s", qUtf8Printable(key), qUtf8Printable(value));另请参阅
qPrintable()qDebug()qInfo()qWarning()qCritical()qFatal()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.
另请参阅
QT_VERSION_STRversion()Calls the message handler with the warning message
message. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. On QNX the message is sent to slogger2. This function does nothing ifQT_NO_WARNING_OUTPUTwas defined during compilation; it exits if at the nth warning corresponding to the counter in environment variableQT_FATAL_WARNINGS. That is, if the environment variable contains the value 1, it will exit on the 1st message; if it contains the value 10, it will exit on the 10th message. Any non-numeric value is equivalent to 1.This function takes a format string and a list of arguments, similar to the C printf() function. The format should be a Latin-1 string.
范例:
void f(int c) { if (c > 200) qWarning("f: bad argument, c == %d", c); }If you include <QtDebug>, a more convenient syntax is also available:
qWarning() << "Brush:" << myQBrush << "Other value:" << i;This syntax inserts a space between each item, and appends a newline at the end.
To suppress the output at runtime, install your own message handler with
qInstallMessageHandler().另请参阅
qDebug()qInfo()qCritical()qFatal()qInstallMessageHandler()调试 TechniquesUses
Q_CHECK_PTRonp, then returnsp.This can be used as an inline version of
Q_CHECK_PTR.Returns the value of the environment variable with name
varName作为QByteArray. If no variable by that name is found in the environment, this function returns a default-constructedQByteArray.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.
To convert the data to a
QStringusefromLocal8Bit().注意
on desktop Windows, 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.另请参阅
qputenv()qEnvironmentVariable()qEnvironmentVariableIsSet()qEnvironmentVariableIsEmpty()此函数设置
valueof the environment variable namedvarName. 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.注意
was introduced because putenv() from the standard C library was deprecated in VC2005 (and later versions). uses the replacement function in VC, and calls the standard C library’s implementation on all other platforms.
另请参阅
qgetenv()qEnvironmentVariable()Thread-safe version of the standard C++
rand()函数。Returns a value between 0 and
RAND_MAX(defined in<cstdlib>and<stdlib.h>), the next number in the current sequence of pseudo-random integers.使用
qsrand()to initialize the pseudo-random number generator with a seed value. Seeding must be performed at least once on each thread. If that step is skipped, then the sequence will be pre-seeded with a constant value.注意
This function is deprecated. In new applications, use
QRandomGenerator代替。另请参阅
qsrand()QRandomGeneratorThread-safe version of the standard C++
srand()函数。Sets the argument
seedto be used to generate a new random number sequence of pseudo random integers to be returned byqrand().The sequence of random numbers generated is deterministic per thread. For example, if two threads call qsrand(1) and subsequently call
qrand(), the threads will get the same random number sequence.注意
This function is deprecated. In new applications, use
QRandomGenerator代替。另请参阅
qrand()QRandomGeneratorThe 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.若
n>= 0, all occurrences of%nin the resulting string are replaced with a decimal representation ofn. In addition, depending onn‘s value, the translation text may vary.Meta data and comments can be passed as documented for
tr(). In addition, it is possible to supply a source string template like that:
//% <C string>or
\begincomment% <C string> \endcomment范例:
//% "%n fooish bar(s) found.\n" //% "Do you want to continue?" QString text = qtTrId("qtn_foo_bar", n);Creating QM files suitable for use with this function requires passing the
-idbasedoption to thelrelease工具。警告
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.
另请参阅
tr()translate()国际化 with QtThis function deletes the variable
varNamefrom the environment.返回
true当成功时。另请参阅
qputenv()qgetenv()qEnvironmentVariable()这是 typedef 对于
void (*)(), a pointer to a function that takes no arguments and returns void.Typedef 为
signed short。此类型保证在 Qt 支持的所有平台为 16 位。Typedef 为
signed int。此类型保证在 Qt 支持的所有平台为 32 位。Typedef 为
long long int(__int64在 Windows)。此类型保证在 Qt 支持的所有平台为 64 位。可以创建此类型的文字使用
Q_INT64_C()宏:qint64 value = Q_INT64_C(932838457459459);另请参阅
Q_INT64_C()quint64qlonglongTypedef 为
signed char。此类型保证在 Qt 支持的所有平台为 8 位。用于以有符号整数表示指针的整型 (对哈希等有用)。
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.
另请参阅
qptrdiffqint32qint64Typedef 为
long long int(__int64在 Windows)。这如同qint64.另请参阅
qulonglongqint64用于表示指针差异的整型。
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.
注意:qptrdiff 是有符号的。使用 quintptr 为无符号值。
另请参阅
quintptrqint32qint64Typedef 为
double除非配置 Qt 采用-qreal float选项。Typedef 为
unsigned short。此类型保证在 Qt 支持的所有平台为 16 位。Typedef 为
unsigned int。此类型保证在 Qt 支持的所有平台为 32 位。Typedef 为
unsigned long long int(unsigned __int64在 Windows)。此类型保证在 Qt 支持的所有平台为 64 位。可以创建此类型的文字使用
Q_UINT64_C()宏:quint64 value = Q_UINT64_C(932838457459459);另请参阅
Q_UINT64_C()qint64qulonglongTypedef 为
unsigned char。此类型保证在 Qt 支持的所有平台为 8 位。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.
另请参阅
qptrdiffquint32quint64Typedef 为
unsigned long long int(unsigned __int64在 Windows)。这如同quint64.另请参阅
quint64qlonglong方便 typedef 为
unsigned char.方便 typedef 为
unsigned int.方便 typedef 为
unsigned long.方便 typedef 为
unsigned short.Integral type providing Posix’
ssize_t对于所有平台。This type is guaranteed to be the same size as a
size_ton all platforms supported by Qt.Note that qsizetype is signed. Use
size_t对于无符号值。另请参阅
qptrdiffThis 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.
常量
描述
QtDebugMsg
生成的消息,由
qDebug()函数。QtInfoMsg
生成的消息,由
qInfo()函数。QtWarningMsg
生成的消息,由
qWarning()函数。QtCriticalMsg
生成的消息,由
qCritical()函数。QtFatalMsg
生成的消息,由
qFatal()函数。QtSystemMsg
QtInfoMsg在 Qt 5.5 添加。另请参阅
QtMessageHandlerqInstallMessageHandler()这是采用以下签名的函数指针的 typedef:
void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);另请参阅
QtMsgTypeqInstallMessageHandler()这是采用以下签名的函数指针的 typedef:
void myMsgHandler(QtMsgType, const char *);This typedef is deprecated, you should use
QtMessageHandler代替。另请参阅
QtMsgTypeQtMessageHandlerqInstallMsgHandler()qInstallMessageHandler()