QtCore

The QtCore module contains the core classes, including the event loop and Qt’s signal and slot mechanism. It also includes platform independent abstractions for animations, state machines, threads, mapped files, shared memory, regular expressions, and user and application settings.

Classes

QAbstractAnimation

QFile

QModelRoleDataSpan

QStorageInfo

QAbstractEventDispatcher

QFileDevice

QMutex

QStringConverter

QAbstractItemModel

QFileInfo

QMutexLocker

QStringConverterBase

QAbstractListModel

QFileSelector

QNativeIpcKey

QStringDecoder

QAbstractNativeEventFilter

QFileSystemWatcher

QObject

QStringEncoder

QAbstractProxyModel

QGenericArgument

QObjectCleanupHandler

QStringListModel

QAbstractTableModel

QGenericReturnArgument

QOperatingSystemVersion

QSysInfo

QAnimationGroup

QIdentityProxyModel

QOperatingSystemVersionBase

QSystemSemaphore

QBasicTimer

QIODevice

QParallelAnimationGroup

Qt

QBitArray

QIODeviceBase

QPauseAnimation

QTemporaryDir

QBluetoothPermission

QItemSelection

QPermission

QTemporaryFile

QBuffer

QItemSelectionModel

QPersistentModelIndex

QTextBoundaryFinder

QByteArray

QItemSelectionRange

QPluginLoader

QTextStream

QByteArrayMatcher

QJsonDocument

QPoint

QThread

QCalendar

QJsonParseError

QPointF

QThreadPool

QCalendarPermission

QJsonValue

QProcess

QTime

QCameraPermission

QKeyCombination

QProcessEnvironment

QTimeLine

QCborError

QLibrary

QPropertyAnimation

QTimer

QCborStreamReader

QLibraryInfo

QRandomGenerator

QTimerEvent

QCborStreamWriter

QLine

QReadLocker

QTimeZone

QChar

QLineF

QReadWriteLock

QTranslator

QChildEvent

QLocale

QRect

QTransposeProxyModel

QCollator

QLocationPermission

QRectF

QTypeRevision

QCollatorSortKey

QLockFile

QRecursiveMutex

QUrl

QCommandLineOption

QLoggingCategory

QRegularExpression

QUrlQuery

QCommandLineParser

QMargins

QRegularExpressionMatch

QUuid

QConcatenateTablesProxyModel

QMarginsF

QRegularExpressionMatchIterator

QVariant

QContactsPermission

QMessageAuthenticationCode

QResource

QVariantAnimation

QCoreApplication

QMessageLogContext

QRunnable

QVersionNumber

QCryptographicHash

QMessageLogger

QSaveFile

QWaitCondition

QDataStream

QMetaClassInfo

QSemaphore

QWinEventNotifier

QDate

QMetaEnum

QSemaphoreReleaser

QWriteLocker

QDateTime

QMetaMethod

QSequentialAnimationGroup

QXmlStreamAttribute

QDeadlineTimer

QMetaObject

QSettings

QXmlStreamAttributes

QDir

QMetaProperty

QSharedMemory

QXmlStreamEntityDeclaration

QDirIterator

QMetaType

QSignalBlocker

QXmlStreamEntityResolver

QDynamicPropertyChangeEvent

QMicrophonePermission

QSignalMapper

QXmlStreamNamespaceDeclaration

QEasingCurve

QMimeData

QSize

QXmlStreamNotationDeclaration

QElapsedTimer

QMimeDatabase

QSizeF

QXmlStreamReader

QEvent

QMimeType

QSocketNotifier

QXmlStreamWriter

QEventLoop

QModelIndex

QSortFilterProxyModel

QEventLoopLocker

QModelRoleData

QStandardPaths

Enums

QCborKnownTags

This enum contains a list of CBOR tags, known at the time of the Qt implementation. This list is not meant to be complete and contains only tags that are either backed by an RFC or specifically used by the Qt implementation.

The authoritative list is maintained by IANA in the CBOR tag registry.

The following tags are interpreted by QCborValue during decoding and will produce objects with extended Qt types, and it will use those tags when encoding the same extended types.

Additionally, if a QCborValue containing a QByteArray is tagged using one of ExpectedBase64url, ExpectedBase64 or ExpectedBase16, QCborValue will use the expected encoding when converting to JSON (see QCborValue::toJsonValue).

See also

QCborTag, QCborStreamWriter::append(QCborTag), isTag(), QCborStreamReader::toTag(), QCborValue::isTag(), QCborValue::tag().

Member

Value

Description

Base64

34

Indicates that the string contains data encoded using Base64.

Base64url

33

Indicates that the string contains data encoded using Base64url.

Bigfloat

5

Similar to Decimal, but the exponent is a power of 2 instead.

COSE_Encrypt

96

An Encrypt map as specified by RFC 8152 (CBOR Object Signing and Encryption).

COSE_Encrypt0

16

An Encrypt0 map as specified by RFC 8152 (CBOR Object Signing and Encryption).

COSE_Mac

97

A Mac map as specified by RFC 8152 (CBOR Object Signing and Encryption).

COSE_Mac0

17

A Mac0 map as specified by RFC 8152 (CBOR Object Signing and Encryption).

COSE_Sign

98

A Sign map as specified by RFC 8152 (CBOR Object Signing and Encryption).

COSE_Sign1

18

A Sign1 map as specified by RFC 8152 (CBOR Object Signing and Encryption).

DateTimeString

0

QDateTime

Decimal

4

A decimal fraction, encoded as an array of two integers: the first is the exponent of the power of 10, the second the integral mantissa. The value 273.15 would be encoded as array [-2, 27315].

EncodedCbor

24

Indicates that the byte array contains a CBOR stream.

ExpectedBase16

23

Indicates that the byte array should be encoded using Base16 (hex) if the stream is converted to JSON.

ExpectedBase64

22

Indicates that the byte array should be encoded using Base64 if the stream is converted to JSON.

ExpectedBase64url

21

Indicates that the byte array should be encoded using Base64url if the stream is converted to JSON.

MimeMessage

36

Indicates that the string contains a MIME message (according to RFC 2045).

NegativeBignum

3

A negative number of arbitrary length, encoded as the absolute value of that number, minus one. For example, a byte array containing byte value 0x02 followed by 8 zero bytes represents the number -265 - 1.

PositiveBignum

2

A positive number of arbitrary length, encoded as a byte array in network byte order. For example, the number 264 is represented by a byte array containing the byte value 0x01 followed by 8 zero bytes.

RegularExpression

35

Indicates that the string contains a Perl-Compatible Regular Expression pattern.

Signature

55799

No change in interpretation; this tag can be used as the outermost tag in a CBOR stream as the file header.

UnixTime_t

1

QDateTime (only in decoding)

Url

32

QUrl

Uuid

37

QUuid


QCborSimpleType

This enum contains the possible “Simple Types” for CBOR. Simple Types range from 0 to 255 and are types that carry no further value.

The following values are currently known:

Qt CBOR API supports encoding and decoding any Simple Type, whether one of those above or any other value.

Applications should only use further values if a corresponding specification has been published, otherwise interpretation and validation by the remote may fail. Values 24 to 31 are reserved and must not be used.

The current authoritative list is maintained by IANA in the Simple Values registry.

See also

QCborStreamWriter::append(QCborSimpleType), isSimpleType(), toSimpleType(), QCborValue::isSimpleType(), QCborValue::toSimpleType().

Member

Value

Description

False_

20

A “false” boolean.

Null

22

Absence of value (null).

True_

21

A “true” boolean.

Undefined

23

Missing or deleted value, usually an error.


QtMsgType

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

QtInfoMsg was added in Qt 5.5.

See also

QtMessageHandler, qInstallMessageHandler().

Member

Value

Description

QtCriticalMsg

2

A message generated by the qCritical() function.

QtDebugMsg

0

A message generated by the qDebug() function.

QtFatalMsg

3

A message generated by the qFatal() function.

QtInfoMsg

4

A message generated by the qInfo() function.

QtSystemMsg

TODO

TODO

QtWarningMsg

1

A message generated by the qWarning() function.

Attributes

PYQT_VERSION: int

This is a read-only attribute.

TODO


PYQT_VERSION_STR: str

This is a read-only attribute.

TODO


QT_VERSION: int

This is a read-only attribute.

This macro expands to a numeric value of the same form as QT_VERSION_CHECK() constructs, that specifies the version of Qt with which code using it is compiled. For example, if you compile your application with Qt 6.1.2, the QT_VERSION macro will expand to 0x060102, the same as QT_VERSION_CHECK(6, 1, 2). Note that this need not agree with the version the application will find itself using at runtime.

You can use QT_VERSION to select the latest Qt features where available while falling back to older implementations otherwise. Using QT_VERSION_CHECK() for the value to compare with is recommended.

Example:

# #if QT_VERSION >= 0x040100
#     QIcon icon = style()->standardIcon(QStyle::SP_TrashIcon);
# #else
#     QPixmap pixmap = style()->standardPixmap(QStyle::SP_TrashIcon);
#     QIcon icon(pixmap);
# #endif

See also

QT_VERSION_STR, QT_VERSION_CHECK(), qVersion().


QT_VERSION_STR: str

This is a read-only attribute.

This macro expands to a string that specifies Qt’s version number (for example, “6.1.2”). This is the version with which the application is compiled. This may be a different version than the version the application will find itself using at runtime.

See also

qVersion(), QT_VERSION.

Functions

pyqtClassInfo(str, str)

TODO


pyqtEnum(enum.Enum)

TODO


pyqtPickleProtocol() Optional[int]

TODO


pyqtRemoveInputHook()

TODO


pyqtRestoreInputHook()

TODO


pyqtSetPickleProtocol(Optional[int])

TODO


pyqtSlot(Any, name: str = None, result: str = None) Any

TODO


Q_ARG(Any, Any) QGenericArgument

This macro takes a Type and a value of that type and returns a QMetaMethodArgument, which can be passed to the template invokeMethod() with the Args &&... arguments.

See also

Q_RETURN_ARG().


Q_RETURN_ARG(Any) QGenericReturnArgument

This macro takes a Type and a non-const reference to a value of that type and returns a QMetaMethodReturnArgument, which can be passed to the template invokeMethod() with the Args &&... arguments.

See also

Q_ARG().


qAbs(float) float

TODO


qAddPostRoutine(Callable[..., None])

TODO


qAddPreRoutine(Callable[[], None])

TODO


qChecksum(Union[QByteArray, bytes, bytearray, memoryview], standard: ChecksumType = ChecksumIso3309) int

Returns the CRC-16 checksum of data.

The checksum is independent of the byte order (endianness) and will be calculated accorded to the algorithm published in standard. By default the algorithm published in ISO 3309 (ChecksumIso3309) is used.

Note: This function is a 16-bit cache conserving (16 entry table) implementation of the CRC-16-CCITT algorithm.


qCompress(bytes, compressionLevel: int = -1) QByteArray

TODO


qCompress(Union[QByteArray, bytes, bytearray, memoryview], compressionLevel: int = -1) QByteArray

Compresses the data byte array and returns the compressed data in a new byte array.

The compressionLevel parameter specifies how much compression should be used. Valid values are between 0 and 9, with 9 corresponding to the greatest compression (i.e. smaller compressed data) at the cost of using a slower algorithm. Smaller values (8, 7, …, 1) provide successively less compression at slightly faster speeds. The value 0 corresponds to no compression at all. The default value is -1, which specifies zlib’s default compression.

See also

qUncompress(const QByteArray &data).


qCritical(str)

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

Example:

# 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(str)

TODO


qEnvironmentVariable(str) str

TODO


qEnvironmentVariable(str, Optional[str]) str

TODO


qEnvironmentVariableIntValue(str) (int, bool)

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

Equivalent to

#     qgetenv(varName).toInt(ok, 0)

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

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


qEnvironmentVariableIsEmpty(str) bool

Returns whether the environment variable varName is empty.

Equivalent to

#     qgetenv(varName).isEmpty()

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


qEnvironmentVariableIsSet(str) bool

Returns whether the environment variable varName is set.

Equivalent to

#     !qgetenv(varName).isNull()

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


qFatal(str)

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.

Example:

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


qFloatDistance(float, float) int

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

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

See also

qFuzzyCompare().


qFormatLogMessage(QtMsgType, QMessageLogContext, Optional[str]) str

TODO


qFuzzyCompare(QLineF, QLineF) bool

TODO


qFuzzyCompare(QMarginsF, QMarginsF) bool

TODO


qFuzzyCompare(float, float) bool

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

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

# // 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.


qFuzzyCompare(QPointF, QPointF) bool

TODO


qFuzzyCompare(QRectF, QRectF) bool

TODO


qFuzzyCompare(QSizeF, QSizeF) bool

TODO


qFuzzyIsNull(QLineF) bool

TODO


qFuzzyIsNull(QMarginsF) bool

TODO


qFuzzyIsNull(float) bool

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


qFuzzyIsNull(QPointF) bool

TODO


qFuzzyIsNull(QRectF) bool

TODO


qFuzzyIsNull(QSizeF) bool

TODO


qInf() float

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

See also

qIsInf().


qInfo(str)

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 if QT_NO_INFO_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.

Example:

# 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 QDebug object that is configured to use the QtInfoMsg 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 runtime, install your own message handler using qInstallMessageHandler().


qInstallMessageHandler(Optional[Callable[[QtMsgType, QMessageLogContext, Optional[str]], None]]) Optional[Callable[[QtMsgType, QMessageLogContext, Optional[str]], None]]

TODO


qIsFinite(float) bool

Returns true if the double d is a finite number.


qIsInf(float) bool

Returns true if the double d is equivalent to infinity.

See also

qInf().


qIsNaN(float) bool

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


qQNaN() float

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

See also

qIsNaN().


qRegisterResourceData(int, bytes, bytes, bytes) bool

TODO


qRemovePostRoutine(Callable[..., None])

TODO


qRound(float) int

TODO


qRound64(float) int

TODO


qSetFieldWidth(int) QTextStreamManipulator

Equivalent to setFieldWidth()(width).


qSetMessagePattern(Optional[str])

TODO


qSetPadChar(str) QTextStreamManipulator

Equivalent to setPadChar()(ch).


qSetRealNumberPrecision(int) QTextStreamManipulator

Equivalent to setRealNumberPrecision()(precision).


qSNaN() float

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


QT_TR_NOOP(str) str

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

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

Example:

# 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(str, str) str

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

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

Example:

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

See also

QT_TR_NOOP(), QT_TRANSLATE_NOOP3().


qUncompress(bytes) QByteArray

TODO


qUncompress(Union[QByteArray, bytes, bytearray, memoryview]) QByteArray

Uncompresses the data byte array and returns a new byte array with the uncompressed data.

Returns an empty QByteArray if the input data was corrupt.

This function will uncompress data compressed with qCompress() from this and any earlier Qt version, back to Qt 3.1 when this feature was added.

Note: If you want to use this function to uncompress external data that was compressed using zlib, you first need to prepend a four byte header to the byte array containing the data. The header must contain the expected length (in bytes) of the uncompressed data, expressed as an unsigned, big-endian, 32-bit integer. This number is just a hint for the initial size of the output buffer size, though. If the indicated size is too small to hold the result, the output buffer size will still be increased until either the output fits or the system runs out of memory. So, despite the 32-bit header, this function, on 64-bit platforms, can produce more than 4GiB of output.

Note: In Qt versions prior to Qt 6.5, more than 2GiB of data worked unreliably; in Qt versions prior to Qt 6.0, not at all.

See also

qCompress().


qUnregisterResourceData(int, bytes, bytes, bytes) bool

TODO


qVersion() str

Returns the version number of Qt at runtime as a string (for example, “6.1.2”). This may be a different version than the version the application was compiled with.


qWarning(str)

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 if QT_NO_WARNING_OUTPUT was defined during compilation; it exits if at the nth warning corresponding to the counter in environment variable QT_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.

Example:

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


qYieldCpu()

Pauses the execution of the current thread for an unspecified time, using hardware instructions, without de-scheduling this thread. This function is meant to be used in high-throughput loops where the code expects another thread to modify an atomic variable. This is completely different from yieldCurrentThread(), which is an OS-level operation that may take the whole thread off the CPU and allow other threads (possibly belonging to other processes) to run.

So, instead of

while (!condition)
    ;

one should write

while (!condition)
    qYieldCpu();

This is useful both with and without hardware multithreading on the same core. In the case of hardware threads, it serves to prevent further speculative execution filling up the pipeline, which could starve the sibling thread of resources. Across cores and higher levels of separation, it allows the cache coherency protocol to allocate the cache line being modified and inspected to the logical processor whose result this code is expecting.

It is also recommended to loop around code that does not modify the global variable, to avoid contention in exclusively obtaining the memory location. Therefore, an atomic modification loop such as a spinlock acquisition should be:

while (true) {
    while (!readOnlyCondition(atomic))
        qYieldCpu();
    if (modify(atomic))
        break;
}

On x86 processors and on RISC-V processors with the Zihintpause extension, this will emit the PAUSE instruction, which is ignored on processors that don’t support it; on ARMv7 or later ARM processors, it will emit the YIELD instruction.