<QtGlobal> - 全局 Qt 聲明

<QtGlobal> 頭文件包括基礎全局聲明。它被包括在大多數其它 Qt 頭文件中。 更多...

類型

typedef QtMsgHandler
enum QtMsgType { QtDebugMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtSystemMsg }
typedef qint8
typedef qint16
typedef qint32
typedef qint64
typedef qlonglong
typedef qptrdiff
typedef qreal
typedef quint8
typedef quint16
typedef quint32
typedef quint64
typedef quintptr
typedef qulonglong
typedef uchar
typedef uint
typedef ulong
typedef ushort

函數

T qAbs (const T & value )
const T & qBound (const T & min , const T & value , const T & max )
void qCritical (const char * msg , ...)
void qDebug (const char * msg , ...)
void qFatal (const char * msg , ...)
bool qFuzzyCompare (double p1 , double p2 )
bool qFuzzyCompare (float p1 , float p2 )
QtMsgHandler qInstallMsgHandler (QtMsgHandler handler )
int qMacVersion ()
const T & qMax (const T & value1 , const T & value2 )
const T & qMin (const T & value1 , const T & value2 )
qint64 qRound64 (qreal value )
int qRound (qreal value )
const char * qVersion ()
void qWarning (const char * msg , ...)
T * q_check_ptr (T * pointer )
QByteArray qgetenv (const char * varName )
bool qputenv (const char * varName , const QByteArray & value )
int qrand ()
void qsrand (uint seed )
QString qtTrId (const char * id , int n = -1)
void qt_set_sequence_auto_mnemonic (bool on )
int qt_symbian_exception2Error (const std::exception & aThrow )
void qt_symbian_exception2LeaveL (const std::exception & aThrow )
void qt_symbian_throwIfError (int error )

QT_POINTER_SIZE
QT_REQUIRE_VERSION (int argc , char ** argv , const char * version )
QT_TRANSLATE_NOOP3 ( context , sourceText , comment )
QT_TRANSLATE_NOOP ( context , sourceText )
QT_TRAP_THROWING ( function )
QT_TRID_NOOP ( id )
QT_TRYCATCH_ERROR ( error , function )
QT_TRYCATCH_LEAVING ( function )
QT_TR_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 )
Q_BIG_ENDIAN
Q_BYTE_ORDER
Q_CC_BOR
Q_CC_CDS
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_MWERKS
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_EXPORT
Q_DECL_IMPORT
Q_FOREACH ( variable , container )
Q_FOREVER
const char * Q_FUNC_INFO ()
qint64 Q_INT64_C ( literal )
Q_LIKELY ( expr )
Q_LITTLE_ENDIAN
Q_OS_AIX
Q_OS_BSD4
Q_OS_BSDI
Q_OS_CYGWIN
Q_OS_DARWIN
Q_OS_DGUX
Q_OS_DYNIX
Q_OS_FREEBSD
Q_OS_HPUX
Q_OS_HURD
Q_OS_IRIX
Q_OS_LINUX
Q_OS_LYNX
Q_OS_MAC
Q_OS_MSDOS
Q_OS_NETBSD
Q_OS_OS2
Q_OS_OPENBSD
Q_OS_OS2EMX
Q_OS_OSF
Q_OS_QNX
Q_OS_RELIANT
Q_OS_SCO
Q_OS_SOLARIS
Q_OS_SYMBIAN
Q_OS_ULTRIX
Q_OS_UNIX
Q_OS_UNIXWARE
Q_OS_WIN32
Q_OS_WINCE
quint64 Q_UINT64_C ( literal )
Q_UNLIKELY ( expr )
Q_UNUSED ( name )
Q_WS_S60
Q_WS_X11
Q_WS_MAC
Q_WS_QPA
Q_WS_QWS
Q_WS_WIN
foreach ( variable , container )
forever
const char * qPrintable (const QString & str )

全局聲明包括 類型 , 函數 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 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 在 Windows)。

Several convenience type definitions are declared: qreal for double , 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; QtMsgHandler is a type definition for a pointer to a function with the signature void myMsgHandler(QtMsgType, const char *) .

函數

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 the qBound () function. You can retrieve the minimum and maximum of two given objects using qMin () 和 qMax () 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: qCritical (), qDebug (), qFatal () 和 qWarning (). 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 () 和 qRound64 (), which both accept a qreal value as their argument returning the value rounded up to the nearest integer and 64-bit integer respectively, the qInstallMsgHandler () function which installs the given QtMsgHandler ,和 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_WIN32 which is defined for Microsoft Windows.

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_TRANSLATE_NOOP () 和 QT_TR_NOOP () macros provide the possibility of marking text for dynamic translation, i.e. translation without changing the stored source text. The Q_ASSERT () 和 Q_ASSERT_X () enables warning messages of various level of refinement. The Q_FOREACH () 和 foreach () macros implement Qt's foreach loop.

The Q_INT64_C () 和 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 0. The qPrintable () macro represent an easy way of printing text.

Finally, the QT_POINTER_SIZE macro expands to the size of a pointer in bytes, and the QT_VERSION and QT_VERSION_STR macros expand to a numeric value or a string, respectively, specifying Qt's version number, i.e the version the application is compiled against.

另請參閱 <QtAlgorithms> and QSysInfo .

類型文檔編製

typedef QtMsgHandler

這是采用以下簽名的函數指針的 typedef:

void myMsgHandler(QtMsgType, const char *);
					

另請參閱 QtMsgType and qInstallMsgHandler ().

enum QtMsgType

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

常量 描述
QtDebugMsg 0 消息的生成是通過 qDebug () 函數。
QtWarningMsg 1 消息的生成是通過 qWarning () 函數。
QtCriticalMsg 2 消息的生成是通過 qCritical () 函數。
QtFatalMsg 3 消息的生成是通過 qFatal () 函數。
QtSystemMsg QtCriticalMsg

另請參閱 QtMsgHandler and qInstallMsgHandler ().

typedef qint8

typedef 對於 signed char 。此類型保證在 Qt 支持的所有平颱為 8 位。

typedef qint16

typedef 對於 signed short 。此類型保證在 Qt 支持的所有平颱為 16 位。

typedef qint32

typedef 對於 signed int 。此類型保證在 Qt 支持的所有平颱為 32 位。

typedef qint64

typedef 對於 long long int ( __int64 在 Windows)。此類型保證在由 Qt 支持的所有平颱都為 64 位。

可以創建此類型的文字使用 Q_INT64_C () 宏:

qint64 value = Q_INT64_C(932838457459459);
					

另請參閱 Q_INT64_C (), quint64 ,和 qlonglong .

typedef qlonglong

typedef 對於 long long int ( __int64 在 Windows)。這如同 qint64 .

另請參閱 qulonglong and qint64 .

typedef qptrdiff

用於錶示指針差異的整型。

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 為無符號值。

另請參閱 quintptr , qint32 ,和 qint64 .

typedef qreal

typedef 對於 double on all platforms except for those using CPUs with ARM architectures. On ARM-based platforms, qreal 是 typedef 對於 float for performance reasons.

typedef quint8

typedef 對於 unsigned char 。此類型保證在 Qt 支持的所有平颱為 8 位。

typedef quint16

typedef 對於 unsigned short 。此類型保證在 Qt 支持的所有平颱為 16 位。

typedef quint32

typedef 對於 無符號 int 。此類型保證在 Qt 支持的所有平颱為 32 位。

typedef quint64

typedef 對於 unsigned long long int ( unsigned __int64 在 Windows)。此類型保證在由 Qt 支持的所有平颱都為 64 位。

可以創建此類型的文字使用 Q_UINT64_C () 宏:

quint64 value = Q_UINT64_C(932838457459459);
					

另請參閱 Q_UINT64_C (), qint64 ,和 qulonglong .

typedef quintptr

Integral type for representing a pointers (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.

另請參閱 qptrdiff , quint32 ,和 quint64 .

typedef qulonglong

typedef 對於 unsigned long long int ( unsigned __int64 在 Windows)。這如同 quint64 .

另請參閱 quint64 and qlonglong .

typedef uchar

方便 typedef 對於 unsigned char .

typedef uint

方便 typedef 對於 無符號 int .

typedef ulong

方便 typedef 對於 unsigned long .

typedef ushort

方便 typedef 對於 unsigned short .

函數文檔編製

T qAbs (const T & value )

比較 value to the 0 of type T and returns the absolute value. Thus if T is double ,那麼 value is compared to (double) 0 .

範例:

int absoluteValue;
int myValue = -4;
absoluteValue = qAbs(myValue);
// absoluteValue == 4
					

const T & qBound (const T & min , const T & value , const T & max )

返迴 value bounded by min and max 。這相當於 qMax ( min , qMin ( value , max )).

範例:

int myValue = 10;
int minValue = 2;
int maxValue = 6;
int boundedValue = qBound(minValue, myValue, maxValue);
// boundedValue == 6
					

另請參閱 qMin () 和 qMax ().

void qCritical (const char * msg , ...)

Calls the message handler with the critical message msg . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger.

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!", qPrintable(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 qInstallMsgHandler ().

另請參閱 qDebug (), qWarning (), qFatal (), qInstallMsgHandler (),和 調試技術 .

void qDebug (const char * msg , ...)

Calls the message handler with the debug message msg . 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. This function does nothing if QT_NO_DEBUG_OUTPUT was 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;
					

采用此句法,函數返迴 QDebug object that is configured to use the QtDebugMsg message 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 qInstallMsgHandler ().

另請參閱 qWarning (), qCritical (), qFatal (), qInstallMsgHandler (),和 調試技術 .

void qFatal (const char * msg , ...)

Calls the message handler with the fatal message msg . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger.

若正使用 默認消息處理程序 this function will abort on Unix systems 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 qInstallMsgHandler ().

另請參閱 qDebug (), qCritical (), qWarning (), qInstallMsgHandler (),和 調試技術 .

[static] bool qFuzzyCompare ( double p1 , double p2 )

比較浮點值 p1 and p2 並返迴 true 若它們被認為相等,否則 false .

Note that comparing values where either p1 or p2 is 0.0 will not work. The solution to this is to compare against values greater than or equal to 1.0.

        // 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 true
					

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

注意: 此函數是 綫程安全 .

該函數在 Qt 4.4 引入。

[static] bool qFuzzyCompare ( float p1 , float p2 )

比較浮點值 p1 and p2 並返迴 true 若它們被認為相等,否則 false .

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

注意: 此函數是 綫程安全 .

該函數在 Qt 4.4 引入。

QtMsgHandler qInstallMsgHandler ( QtMsgHandler handler )

Installs a Qt message handler which has been defined previously. Returns a pointer to the previous message handler (which may be 0).

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 qInstallMsgHandler(0) .

範例:

#include <qapplication.h>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput(QtMsgType type, const char *msg)
{
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}
int main(int argc, char **argv)
{
    qInstallMsgHandler(myMessageOutput);
    QApplication app(argc, argv);
    ...
    return app.exec();
}
					

另請參閱 qDebug (), qWarning (), qCritical (), qFatal (), QtMsgType ,和 調試技術 .

int qMacVersion ()

使用 QSysInfo::MacintoshVersion 代替。

另請參閱 QSysInfo .

const T & qMax (const T & value1 , const T & value2 )

Returns the maximum of value1 and value2 .

範例:

int myValue = 6;
int yourValue = 4;
int maxValue = qMax(myValue, yourValue);
// maxValue == myValue
					

另請參閱 qMin () 和 qBound ().

const T & qMin (const T & value1 , const T & value2 )

Returns the minimum of value1 and value2 .

範例:

int myValue = 6;
int yourValue = 4;
int minValue = qMin(myValue, yourValue);
// minValue == yourValue
					

另請參閱 qMax () 和 qBound ().

qint64 qRound64 ( qreal value )

圓整 value 到最近 64 位整數。

範例:

qreal valueA = 42949672960.3;
qreal valueB = 42949672960.7;
int roundedValueA = qRound(valueA);
// roundedValueA = 42949672960
int roundedValueB = qRound(valueB);
// roundedValueB = 42949672961
					

int qRound ( qreal value )

圓整 value 到最近整數。

範例:

qreal valueA = 2.3;
qreal valueB = 2.7;
int roundedValueA = qRound(valueA);
// roundedValueA = 2
int roundedValueB = qRound(valueB);
// roundedValueB = 3
					

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.

另請參閱 QT_VERSION_STR .

void qWarning (const char * msg , ...)

調用消息處理程序采用警告消息 msg . If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger. This function does nothing if QT_NO_WARNING_OUTPUT was defined during compilation; it exits if the environment variable QT_FATAL_WARNINGS 有定義。

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 qInstallMsgHandler ().

另請參閱 qDebug (), qCritical (), qFatal (), qInstallMsgHandler (),和 調試技術 .

T * q_check_ptr ( T * pointer )

Users Q_CHECK_PTR on pointer , then returns pointer .

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 . To get the variable string, use QByteArray::constData ().

注意: qgetenv() was introduced because getenv() from the standard C library was deprecated in VC2005 (and later versions). qgetenv() uses the new replacement function in VC, and calls the standard C library's implementation on all other platforms.

另請參閱 qputenv ().

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

此函數設置 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.

注意: 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.

另請參閱 qgetenv ().

int qrand ()

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.

該函數在 Qt 4.2 引入。

另請參閱 qsrand ().

void qsrand ( uint seed )

Thread-safe version of the standard C++ srand() 函數。

Sets the argument seed to be used to generate a new random number sequence of pseudo random integers to be returned by qrand ().

The sequence of random numbers generated is deterministic per thread. For example, if two threads call qsrand(1) and subsequently calls qrand (), the threads will get the same random number sequence.

該函數在 Qt 4.2 引入。

另請參閱 qrand ().

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.

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:

//% <C string>

or

/* % <C string> */

範例:

    //% "%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 -idbased 選項到 lrelease 工具。

警告: 此方法纔可重入若有安裝所有翻譯器 before 調用此方法。不支持在履行翻譯時,安裝或移除翻譯器。這樣做可能會導緻崩潰或其它不期望行為。

注意: 此函數是 可重入 .

該函數在 Qt 4.6 引入。

另請參閱 QObject::tr (), QCoreApplication::translate (),和 Qt 國際化 .

void qt_set_sequence_auto_mnemonic ( bool on )

Enables automatic mnemonics on Mac if on is true; otherwise this feature is disabled.

Note that this function is only available on Mac where mnemonics are disabled by default.

To access to this function, use an extern declaration: extern void qt_set_sequence_auto_mnemonic(bool b);

另請參閱 QShortcut .

int qt_symbian_exception2Error (const std::exception & aThrow )

Convert a caught standard C++ exception aThrow to a Symbian error code

警告: This function is only available on Symbian.

另請參閱 qt_symbian_throwIfError () 和 qt_symbian_exception2LeaveL ().

void qt_symbian_exception2LeaveL (const std::exception & aThrow )

Convert a caught standard C++ exception aThrow to a Symbian leave

警告: This function is only available on Symbian.

另請參閱 qt_symbian_throwIfError () 和 qt_symbian_exception2Error ().

void qt_symbian_throwIfError ( int error )

Throws an exception if the error parameter is a symbian error code. This is the exception throwing equivalent of Symbian's User::LeaveIfError.

警告: This function is only available on Symbian.

另請參閱 qt_symbian_exception2LeaveL () 和 qt_symbian_exception2Error ().

宏文檔編製

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").

範例:

#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();
}
					

QT_TRANSLATE_NOOP3 ( context , sourceText , comment )

Marks the string literal sourceText for dynamic translation in the given context 和采用 comment , i.e the stored sourceText will not be altered. The context is typically a class and also needs to be specified as string literal. The string literal comment will be available for translators using e.g. Qt Linguist.

The macro expands to anonymous struct of the two string literals passed as sourceText and comment .

範例:

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 4.4 引入。

另請參閱 QT_TR_NOOP (), QT_TRANSLATE_NOOP (),和 Qt 國際化 .

QT_TRANSLATE_NOOP ( context , sourceText )

Marks the string literal sourceText for dynamic translation in the given context ; i.e, the stored sourceText will not be altered. The context is typically a class and also needs to be specified as string literal.

The macro 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 (),和 Qt 國際化 .

QT_TRAP_THROWING ( function )

TRAP leaves from Symbian function and throws an appropriate standard C++ exception instead. This must be used when calling Symbian OS leaving functions from inside Qt or standard C++ code, so that the code can respond correctly to the exception.

警告: This macro is only available on Symbian.

範例:

// A Symbian leaving function is being called within a Qt function.
// Any leave must be converted to an exception
CAknTitlePane* titlePane = S60->titlePane();
if (titlePane) {
    TPtrC captionPtr(qt_QString2TPtrC(caption));
    QT_TRAP_THROWING(titlePane->SetTextL(captionPtr));
}
					

另請參閱 QT_TRYCATCH_ERROR () 和 QT_TRYCATCH_LEAVING ().

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 .

範例:

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);
}
					

該函數在 Qt 4.6 引入。

另請參閱 qtTrId () 和 Qt 國際化 .

QT_TRYCATCH_ERROR ( error , function )

Catch standard C++ exceptions from a function and convert them to a Symbian OS error code, or KErrNone if there is no exception. This must be used inside Qt or standard C++ code when using exception throwing code (practically anything) and returning an error code to Symbian OS.

警告: This macro is only available on Symbian.

範例:

// An exception might be thrown in this Symbian TInt error returning function.
// It is caught and translated to an error code
TInt QServerApp::Connect(const QString &serverName)
{
    TPtrC name;
    TInt err;
    QT_TRYCATCH_ERROR(err, name.Set(qt_QString2TPtrC(serverName)));
    if (err != KErrNone)
        return err;
    return iServer.Connect(name);
}
					

}

另請參閱 QT_TRYCATCH_LEAVING () 和 QT_TRAP_THROWING ().

QT_TRYCATCH_LEAVING ( function )

Catch standard C++ exceptions from function and convert them to Symbian OS leaves. This must be used inside Qt or standard C++ code when using exception throwing code (practically anything) and returning to Symbian OS from a leaving function. For example inside a Symbian active object's RunL function implemented with Qt code.

警告: This macro is only available on Symbian.

範例:

// This active object signals Qt code
// Exceptions from the Qt code must be converted to Symbian OS leaves for the active scheduler
void QWakeUpActiveObject::RunL()
{
    iStatus = KRequestPending;
    SetActive();
    QT_TRYCATCH_LEAVING(m_dispatcher->wakeUpWasCalled());
}
					

另請參閱 QT_TRAP_THROWING () 和 QT_TRYCATCH_ERROR ().

QT_TR_NOOP ( sourceText )

Marks the string literal sourceText for dynamic translation in the current context (class), i.e the stored sourceText will not be altered.

The macro 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 except that it tells lupdate that the source string is encoded in UTF-8. Corresponding variants exist in the QT_TRANSLATE_NOOP () family of macros, too. Note that using these macros is not required if CODECFORTR is already set to UTF-8 in the qmake project file.

另請參閱 QT_TRANSLATE_NOOP () 和 Qt 國際化 .

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.

可以使用 QT_VERSION 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_STR and qVersion ().

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 .

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.

另請參閱 qVersion () 和 QT_VERSION .

void Q_ASSERT ( bool test )

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

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

範例:

// File: div.cpp
#include <QtGlobal>
int divide(int a, int b)
{
    Q_ASSERT(b != 0);
    return a / b;
}
					

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

ASSERT: "b == 0" in file div.cpp, line 7
					

另請參閱 Q_ASSERT_X (), qFatal (),和 調試技術 .

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 為 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.

範例:

// File: div.cpp
#include <QtGlobal>
int divide(int a, int b)
{
    Q_ASSERT_X(b != 0, "divide", "division by zero");
    return a / b;
}
					

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

ASSERT failure in divide: "division by zero", file div.cpp, line 7
					

另請參閱 Q_ASSERT (), qFatal (),和 調試技術 .

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.

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
...
#endif
					

另請參閱 Q_BYTE_ORDER and Q_LITTLE_ENDIAN .

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.

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
...
#endif
or
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
...
#endif
					

另請參閱 Q_BIG_ENDIAN and Q_LITTLE_ENDIAN .

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_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_MWERKS

Defined if the application is compiled using Metrowerks CodeWarrior.

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 )

pointer is 0, prints a warning message containing the source code's file name and line number, saying that the program ran out of memory.

Q_CHECK_PTR does nothing if QT_NO_DEBUG was defined during compilation.

範例:

int *a;
Q_CHECK_PTR(a = new int[80]);   // WRONG!
a = new (nothrow) int[80];      // Right
Q_CHECK_PTR(a);
					

另請參閱 qWarning () 和 調試技術 .

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.
  • Q_MOVABLE_TYPE specifies that Type has a constructor and/or a destructor but can be moved in memory using memcpy() .
  • 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:

struct Point2D
{
    int x;
    int y;
};
Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_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);
					

Q_DECL_EXPORT

This macro marks a symbol for shared library export (see 創建共享庫 ).

另請參閱 Q_DECL_IMPORT .

Q_DECL_IMPORT

This macro declares a symbol to be an import from a shared library (see 創建共享庫 ).

另請參閱 Q_DECL_EXPORT .

Q_FOREACH ( variable , container )

如同 foreach( variable , container ).

此宏可用,甚至 no_keywords 的指定是使用 .pro 文件的 CONFIG 變量。

另請參閱 foreach ().

Q_FOREVER

如同 forever .

此宏可用,甚至 no_keywords 的指定是使用 .pro 文件的 CONFIG 變量。

另請參閱 foreach ().

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 ()。例如,此函數:

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: 4

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

qint64 Q_INT64_C ( literal )

包裹有符號 64 位整數 literal 以獨立於平颱的方式。

範例:

qint64 value = Q_INT64_C(932838457459459);
					

另請參閱 qint64 and Q_UINT64_C ().

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.

範例:

    // the condition inside the "if" will be successful most of the times
    for (int i = 1; i <= 365; i++) {
        if (Q_LIKELY(isWorkingDay(i))) {
            ...
        }
        ...
    }
					

該函數在 Qt 4.8 引入。

另請參閱 Q_UNLIKELY ().

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.

#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
...
#endif
					

另請參閱 Q_BYTE_ORDER and Q_BIG_ENDIAN .

Q_OS_AIX

Defined on AIX.

Q_OS_BSD4

Defined on Any BSD 4.4 system.

Q_OS_BSDI

Defined on BSD/OS.

Q_OS_CYGWIN

Defined on Cygwin.

Q_OS_DARWIN

Defined on Darwin OS (synonym for Q_OS_MAC ).

Q_OS_DGUX

Defined on DG/UX.

Q_OS_DYNIX

Defined on DYNIX/ptx.

Q_OS_FREEBSD

Defined on FreeBSD.

Q_OS_HPUX

Defined on HP-UX.

Q_OS_HURD

Defined on GNU Hurd.

Q_OS_IRIX

Defined on SGI Irix.

Q_OS_LINUX

Defined on Linux.

Q_OS_LYNX

Defined on LynxOS.

Q_OS_MAC

Defined on MAC OS (synonym for Darwin).

Q_OS_MSDOS

Defined on MS-DOS and Windows.

Q_OS_NETBSD

Defined on NetBSD.

Q_OS_OS2

Defined on OS/2.

Q_OS_OPENBSD

Defined on OpenBSD.

Q_OS_OS2EMX

Defined on XFree86 on OS/2 (not PM).

Q_OS_OSF

Defined on HP Tru64 UNIX.

Q_OS_QNX

Defined on QNX Neutrino.

Q_OS_RELIANT

Defined on Reliant UNIX.

Q_OS_SCO

Defined on SCO OpenServer 5.

Q_OS_SOLARIS

Defined on Sun Solaris.

Q_OS_SYMBIAN

Defined on Symbian.

Q_OS_ULTRIX

Defined on DEC Ultrix.

Q_OS_UNIX

Defined on Any UNIX BSD/SYSV system.

Q_OS_UNIXWARE

Defined on UnixWare 7, Open UNIX 8.

Q_OS_WIN32

Defined on all supported versions of Windows.

Q_OS_WINCE

Defined on Windows CE.

quint64 Q_UINT64_C ( literal )

包裹無符號 64 位整數 literal 以獨立於平颱的方式。

範例:

quint64 value = Q_UINT64_C(932838457459459);
					

另請參閱 quint64 and Q_INT64_C ().

Q_UNLIKELY ( expr )

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

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;
}
					

該函數在 Qt 4.8 引入。

另請參閱 Q_LIKELY ().

Q_UNUSED ( name )

Indicates to the compiler that the parameter with the specified name is 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.

Q_WS_S60

Defined on S60 with the Avkon UI framework.

另請參閱 Q_WS_MAC , Q_WS_WIN , Q_WS_X11 ,和 Q_WS_QWS .

Q_WS_X11

Defined on X11.

另請參閱 Q_WS_MAC , Q_WS_WIN , Q_WS_QWS , Q_WS_QPA ,和 Q_WS_S60 .

Q_WS_MAC

Defined on Mac OS X.

另請參閱 Q_WS_WIN , Q_WS_X11 , Q_WS_QWS , Q_WS_QPA ,和 Q_WS_S60 .

Q_WS_QPA

Defined on Qt for Embedded Linux, Lite version.

另請參閱 Q_WS_MAC , Q_WS_WIN , Q_WS_X11 , Q_WS_QWS ,和 Q_WS_S60 .

Q_WS_QWS

Defined on Qt for Embedded Linux.

另請參閱 Q_WS_MAC , Q_WS_WIN , Q_WS_X11 , Q_WS_QPA ,和 Q_WS_S60 .

Q_WS_WIN

Defined on Windows.

另請參閱 Q_WS_MAC , Q_WS_X11 , Q_WS_QWS , Q_WS_QPA ,和 Q_WS_S60 .

foreach ( variable , container )

此宏用於實現 Qt 的 foreach 循環。 variable parameter is a variable name or variable definition; the container parameter 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
					

另請參閱 Q_FOREACH ().

forever

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 .

const char * qPrintable (const QString & str )

返迴 str 作為 const char * 。這相當於 str .toLocal8Bit().constData().

The char pointer will be invalid after the statement in which qPrintable() is used. This is because the array returned by toLocal8Bit() will fall out of scope.

範例:

qWarning("%s: %s", qPrintable(key), qPrintable(value));
					

另請參閱 qDebug (), qWarning (), qCritical (),和 qFatal ().