QObject Class

The QObject class is the base class of all Qt objects. More...

Header: #include <QObject>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Inherited By:
284 types

Q3DGraphsWidgetItem, Q3DObject, Q3DScene, Q3DTheme, QAbstract3DAxis, QAbstract3DInputHandler, QAbstract3DSeries, QAbstractAnimation, QAbstractAxis, QAbstractDataProxy, QAbstractEventDispatcher, QAbstractHttpServer, QAbstractItemDelegate, QAbstractItemModel, QAbstractItemModelTester, QAbstractNetworkCache, QAbstractOAuth, QAbstractOAuthReplyHandler, QAbstractSeries, QAbstractState, QAbstractTextDocumentLayout, QAbstractTransition, QAccessiblePlugin, QAction, QActionGroup, QAmbientSound, QAudioBufferInput, QAudioBufferOutput, QAudioDecoder, QAudioEngine, QAudioInput, QAudioListener, QAudioOutput, QAudioRoom, QAudioSink, QAudioSource, QAxBaseObject, QAxFactory, QAxScript, QAxScriptManager, QBarModelMapper, QBarSet, QBluetoothDeviceDiscoveryAgent, QBluetoothLocalDevice, QBluetoothServer, QBluetoothServiceDiscoveryAgent, QBoxSet, QButtonGroup, QCamera, QCanBus, QCanBusDevice, QCandlestickModelMapper, QCandlestickSet, QChronoTimer, QClipboard, QCoapClient, QCompleter, QCoreApplication, QCustom3DItem, QDataWidgetMapper, QDBusAbstractAdaptor, QDBusAbstractInterface, QDBusPendingCallWatcher, QDBusServer, QDBusServiceWatcher, QDBusVirtualObject, QDesignerFormEditorInterface, QDesignerFormWindowManagerInterface, QDnsLookup, QDrag, QDtls, QDtlsClientVerifier, QEventLoop, QExtensionFactory, QExtensionManager, QFileSelector, QFileSystemWatcher, QFutureWatcher, QGenericPlugin, QGeoAreaMonitorSource, QGeoCodeReply, QGeoCodingManager, QGeoCodingManagerEngine, QGeoPositionInfoSource, QGeoRouteReply, QGeoRoutingManager, QGeoRoutingManagerEngine, QGeoSatelliteInfoSource, QGeoServiceProvider, QGesture, QGraphicsAnchor, QGraphicsEffect, QGraphicsItemAnimation, QGraphicsObject, QGraphicsScene, QGraphicsTransform, QGraphsTheme, QGrpcClientBase, QGrpcOperation, QGrpcOperationContext, QHelpEngineCore, QHelpFilterEngine, QHelpSearchEngine, QHelpSearchEngineCore, QHttpMultiPart, QIconEnginePlugin, QImageCapture, QImageIOPlugin, QInputDevice, QInputMethod, QIODevice, QItemSelectionModel, QJSEngine, QLayout, QLegendMarker, QLibrary, QLocalServer, QLowEnergyController, QLowEnergyService, QMaskGenerator, QMediaCaptureSession, QMediaDevices, QMediaPlayer, QMediaRecorder, QMimeData, QModbusDevice, QModbusReply, QMovie, QMqttClient, QMqttSubscription, QNearFieldManager, QNearFieldTarget, QNetworkAccessManager, QNetworkCookieJar, QNetworkInformation, QObjectCleanupHandler, QOffscreenSurface, QOpcUaClient, QOpcUaGdsClient, QOpcUaGenericStructHandler, QOpcUaHistoryReadResponse, QOpcUaKeyPair, QOpcUaNode, QOpcUaProvider, QOpenGLContext, QOpenGLContextGroup, QOpenGLDebugLogger, QOpenGLShader, QOpenGLShaderProgram, QOpenGLTimeMonitor, QOpenGLTimerQuery, QOpenGLVertexArrayObject, QPdfDocument, QPdfPageNavigator, QPdfPageRenderer, QPdfWriter, QPieModelMapper, QPieSlice, QPlaceManager, QPlaceManagerEngine, QPlaceReply, QPluginLoader, QQmlComponent, QQmlContext, QQmlEngineExtensionPlugin, QQmlExpression, QQmlExtensionPlugin, QQmlFileSelector, QQmlImageProviderBase, QQmlPropertyMap, QQuick3DObject, QQuickAttachedPropertyPropagator, QQuickImageResponse, QQuickItem, QQuickItemGrabResult, QQuickRenderControl, QQuickTextDocument, QQuickTextureFactory, QQuickWebEngineProfile, QRemoteObjectAbstractPersistedStore, QRemoteObjectNode, QRemoteObjectPendingCallWatcher, QRemoteObjectReplica, QRestAccessManager, QScreen, QScreenCapture, QScroller, QScxmlDataModel, QScxmlInvokableService, QScxmlInvokableServiceFactory, QScxmlStateMachine, QSensor, QSensorBackend, QSensorReading, QSessionManager, QSettings, QSGTexture, QSGTextureProvider, QSharedMemory, QShortcut, QSignalMapper, QSocketNotifier, QSoundEffect, QSpatialSound, QSqlDriver, QSqlDriverPlugin, QStyle, QStyleHints, QStylePlugin, QSvgRenderer, QSyntaxHighlighter, QSystemTrayIcon, Qt3DAnimation::QAbstractAnimation, Qt3DAnimation::QAnimationController, Qt3DAnimation::QAnimationGroup, Qt3DAnimation::QMorphTarget, Qt3DCore::QAbstractAspect, Qt3DCore::QAspectEngine, Qt3DCore::QNode, Qt3DCore::Quick::QQmlAspectEngine, Qt3DInput::QInputDeviceIntegration, Qt3DInput::QKeyEvent, Qt3DInput::QMouseEvent, Qt3DInput::QWheelEvent, Qt3DRender::QGraphicsApiFilter, Qt3DRender::QPickEvent, Qt3DRender::QRenderCapabilities, Qt3DRender::QRenderCaptureReply, Qt3DRender::QStencilOperationArguments, Qt3DRender::QStencilTestArguments, Qt3DRender::QTextureWrapMode, QTcpServer, QTextDocument, QTextObject, QTextToSpeech, QThread, QThreadPool, QTimeLine, QTimer, QTranslator, QUiLoader, QUndoGroup, QUndoStack, QValidator, QValue3DAxisFormatter, QVideoFrameInput, QVideoSink, QVirtualKeyboardAbstractInputMethod, QVirtualKeyboardDictionary, QVirtualKeyboardDictionaryManager, QVirtualKeyboardInputContext, QVirtualKeyboardInputEngine, QVirtualKeyboardObserver, QVirtualKeyboardTrace, QWaylandClient, QWaylandObject, QWaylandQuickShellIntegration, QWaylandSurfaceGrabber, QWaylandView, QWaylandXdgPopup, QWaylandXdgToplevel, QWebChannel, QWebChannelAbstractTransport, QWebEngineClientHints, QWebEngineContextMenuRequest, QWebEngineCookieStore, QWebEngineDownloadRequest, QWebEngineHistory, QWebEngineNavigationRequest, QWebEngineNewWindowRequest, QWebEngineNotification, QWebEnginePage, QWebEngineProfile, QWebEngineUrlRequestInterceptor, QWebEngineUrlRequestJob, QWebEngineUrlSchemeHandler, QWebEngineWebAuthUxRequest, QWebSocket, QWebSocketServer, QWidget, QWindow, QWindowCapture, QWinEventNotifier, and QXYModelMapper

Note: All functions in this class are reentrant.

Note: These functions are also thread-safe:

  • connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
  • connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const
  • connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
  • connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
  • connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
  • disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
  • disconnect(const char *signal, const QObject *receiver, const char *method) const
  • disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
  • deleteLater()

Properties

Public Functions

QObject(QObject *parent = nullptr)
virtual ~QObject()
QBindable<QString> bindableObjectName()
bool blockSignals(bool block)
const QObjectList &children() const
QMetaObject::Connection connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection) const
bool disconnect(const QObject *receiver, const char *method = nullptr) const
bool disconnect(const char *signal = nullptr, const QObject *receiver = nullptr, const char *method = nullptr) const
void dumpObjectInfo() const
void dumpObjectTree() const
QList<QByteArray> dynamicPropertyNames() const
virtual bool event(QEvent *e)
virtual bool eventFilter(QObject *watched, QEvent *event)
T findChild(QAnyStringView name, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
(since 6.7) T findChild(Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T> findChildren(QAnyStringView name, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
(since 6.3) QList<T> findChildren(Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T> findChildren(const QRegularExpression &re, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
bool inherits(const char *className) const
void installEventFilter(QObject *filterObj)
(since 6.4) bool isQuickItemType() const
bool isWidgetType() const
bool isWindowType() const
void killTimer(int id)
(since 6.8) void killTimer(Qt::TimerId id)
virtual const QMetaObject *metaObject() const
bool moveToThread(QThread *targetThread)
QString objectName() const
QObject *parent() const
QVariant property(const char *name) const
void removeEventFilter(QObject *obj)
void setObjectName(const QString &name)
(since 6.4) void setObjectName(QAnyStringView name)
void setParent(QObject *parent)
bool setProperty(const char *name, const QVariant &value)
(since 6.6) bool setProperty(const char *name, QVariant &&value)
bool signalsBlocked() const
int startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)
int startTimer(std::chrono::nanoseconds interval, Qt::TimerType timerType = Qt::CoarseTimer)
QThread *thread() const

Public Slots

void deleteLater()

Signals

void destroyed(QObject *obj = nullptr)
void objectNameChanged(const QString &objectName)

Static Public Members

QMetaObject::Connection connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)
bool disconnect(const QMetaObject::Connection &connection)
bool disconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method)
bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
bool disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
const QMetaObject staticMetaObject
QString tr(const char *sourceText, const char *disambiguation = nullptr, int n = -1)

Protected Functions

virtual void childEvent(QChildEvent *event)
virtual void connectNotify(const QMetaMethod &signal)
virtual void customEvent(QEvent *event)
virtual void disconnectNotify(const QMetaMethod &signal)
bool isSignalConnected(const QMetaMethod &signal) const
int receivers(const char *signal) const
QObject *sender() const
int senderSignalIndex() const
virtual void timerEvent(QTimerEvent *event)
QObjectList
T qobject_cast(QObject *object)
T qobject_cast(const QObject *object)

Macros

Detailed Description

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect(). To avoid never ending notification loops you can temporarily block signals with blockSignals(). The protected functions connectNotify() and disconnectNotify() make it possible to track connections.

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().

Every object has an objectName() and its class name can be found via the corresponding metaObject() (see QMetaObject::className()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the inherits() function.

When an object is deleted, it emits a destroyed() signal. You can catch this signal to avoid dangling references to QObjects.

QObjects can receive events through event() and filter the events of other objects. See installEventFilter() and eventFilter() for details. A convenience handler, childEvent(), can be reimplemented to catch child events.

Last but not least, QObject provides the basic timer support in Qt; see QChronoTimer for high-level support for timers.

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

All Qt widgets inherit QObject. The convenience function isWidgetType() returns whether an object is actually a widget. It is much faster than qobject_cast<QWidget *>(obj) or obj->inherits("QWidget").

Some QObject functions, e.g. children(), return a QObjectList. QObjectList is a typedef for QList<QObject *>.

Thread Affinity

A QObject instance is said to have a thread affinity, or that it lives in a certain thread. When a QObject receives a queued signal or a posted event, the slot or event handler will run in the thread that the object lives in.

Note: If a QObject has no thread affinity (that is, if thread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.

By default, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread() and changed using moveToThread().

All QObjects must live in the same thread as their parent. Consequently:

  • setParent() will fail if the two QObjects involved live in different threads.
  • When a QObject is moved to another thread, all its children will be automatically moved too.
  • moveToThread() will fail if the QObject has a parent.
  • If QObjects are created within QThread::run(), they cannot become children of the QThread object because the QThread does not live in the thread that calls QThread::run().

Note: A QObject's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor, or by calling setParent(). Without this step, the object's member variables will remain in the old thread when moveToThread() is called.

No Copy Constructor or Assignment Operator

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

Auto-Connection

Qt's meta-object system provides a mechanism to automatically connect signals and slots between QObject subclasses and their children. As long as objects are defined with suitable object names, and slots follow a simple naming convention, this connection can be performed at run-time by the QMetaObject::connectSlotsByName() function.

uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created with Qt Widgets Designer. More information about using auto-connection with Qt Widgets Designer is given in the Using a Designer UI File in Your Application section of the Qt Widgets Designer manual.

Dynamic Properties

Dynamic properties can be added to and removed from QObject instances at run-time. Dynamic properties do not need to be declared at compile-time, yet they provide the same advantages as static properties and are manipulated using the same API - using property() to read them and setProperty() to write them.

Dynamic properties are supported by Qt Widgets Designer, and both standard Qt widgets and user-created forms can be given dynamic properties.

Internationalization (I18n)

All QObject subclasses support Qt's translation features, making it possible to translate an application's user interface into different languages.

To make user-visible text translatable, it must be wrapped in calls to the tr() function. This is explained in detail in the Writing Source Code for Translation document.

See also QMetaObject, QPointer, QObjectCleanupHandler, Q_DISABLE_COPY(), and Object Trees & Ownership.

Property Documentation

[bindable] objectName : QString

Note: This property supports QProperty bindings.

This property holds the name of this object

You can find an object by name (and type) using findChild(). You can find a set of objects with findChildren().

qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
       qPrintable(objectName()), newPrecision);

By default, this property contains an empty string.

See also metaObject() and QMetaObject::className().

Member Function Documentation

[explicit invokable] QObject::QObject(QObject *parent = nullptr)

Constructs an object with parent object parent.

The parent of an object may be viewed as the object's owner. For instance, a dialog box is the parent of the OK and Cancel buttons it contains.

The destructor of a parent object destroys all child objects.

Setting parent to nullptr constructs an object with no parent. If the object is a widget, it will become a top-level window.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

See also parent(), findChild(), and findChildren().

[virtual noexcept] QObject::~QObject()

Destroys the object, deleting all its child objects.

All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly.

Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash. We do not recommend holding pointers to child objects from outside the parent. If you still do, the destroyed() signal gives you an opportunity to detect when an object is destroyed.

Warning: Deleting a QObject while it is handling an event delivered to it can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.

See also deleteLater().

[noexcept] bool QObject::blockSignals(bool block)

If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). If block is false, no such blocking will occur.

The return value is the previous value of signalsBlocked().

Note that the destroyed() signal will be emitted even if the signals for this object have been blocked.

Signals emitted while being blocked are not buffered.

See also signalsBlocked() and QSignalBlocker.

[virtual protected] void QObject::childEvent(QChildEvent *event)

This event handler can be reimplemented in a subclass to receive child events. The event is passed in the event parameter.

QEvent::ChildAdded and QEvent::ChildRemoved events are sent to objects when children are added or removed. In both cases you can only rely on the child being a QObject, or if isWidgetType() returns true, a QWidget. (This is because, in the ChildAdded case, the child is not yet fully constructed, and in the ChildRemoved case it might have been destructed already).

QEvent::ChildPolished events are sent to widgets when children are polished, or when polished children are added. If you receive a child polished event, the child's construction is usually completed. However, this is not guaranteed, and multiple polish events may be delivered during the execution of a widget's constructor.

For every child widget, you receive one ChildAdded event, zero or more ChildPolished events, and one ChildRemoved event.

The ChildPolished event is omitted if a child is removed immediately after it is added. If a child is polished several times during construction and destruction, you may receive several child polished events for the same child, each time with a different virtual table.

See also event().

const QObjectList &QObject::children() const

Returns a list of child objects. The QObjectList class is defined in the <QObject> header file as the following:

The first child added is the first object in the list and the last child added is the last object in the list, i.e. new children are appended at the end.

Note that the list order changes when QWidget children are raised or lowered. A widget that is raised becomes the last object in the list, and a widget that is lowered becomes the first object in the list.

See also findChild(), findChildren(), parent(), and setParent().

[static] QMetaObject::Connection QObject::connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.

The Connection handle will be invalid if it cannot create the connection, for example, the parameters were invalid. You can check if the QMetaObject::Connection is valid by casting it to a bool.

This function works in the same way as connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) but it uses QMetaMethod to specify signal and method.

See also connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type).

[static] QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.

You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:

QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
                 label,  SLOT(setNum(int)));

This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:

// WRONG
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
                 label, SLOT(setNum(int value)));

A signal can also be connected to another signal:

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    MyWidget();

signals:
    void buttonClicked();

private:
    QPushButton *myButton;
};

MyWidget::MyWidget()
{
    myButton = new QPushButton(this);
    connect(myButton, SIGNAL(clicked()),
            this, SIGNAL(buttonClicked()));
}

In this example, the MyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates to MyWidget.

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in the same order in which the connections were made, when the signal is emitted.

The function returns a QMetaObject::Connection that represents a handle to a connection if it successfully connects the signal to the slot. The connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of either signal or method, or if their signatures aren't compatible. You can check if the handle is valid by casting it to a bool.

By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection.

Note: Qt::UniqueConnections do not work for lambdas, non-member functions and functors; they only apply to connecting to member functions.

The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)

call qRegisterMetaType() to register the data type before you establish the connection.

Note: This function is thread-safe.

See also disconnect(), sender(), qRegisterMetaType(), Q_DECLARE_METATYPE(), and Differences between String-Based and Functor-Based Connections.

[static] template <typename PointerToMemberFunction, typename Functor> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)

This function overloads connect().

Creates a connection from signal in sender object to functor, and returns a handle to the connection

The signal must be a function declared as a signal in the header. The slot function can be any function or functor that can be connected to the signal. A slot function can be connected to a given signal if the signal has at least as many arguments as the slot function. There must exist implicit conversion between the types of the corresponding arguments in the signal and the slot.

Example:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);

Lambda expressions can also be used:

QByteArray page = ...;
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost("qt-project.org", 80);
QObject::connect(socket, &QTcpSocket::connected, [=] () {
        socket->write("GET " + page + "\r\n");
    });

The connection will automatically disconnect if the sender is destroyed. However, you should take care that any objects used within the functor are still alive when the signal is emitted.

For this reason, it is recommended to use the overload of connect() that also takes a QObject as a receiver/context. It is possible to disable the usage of the context-less overload by defining the QT_NO_CONTEXTLESS_CONNECT macro.

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe.

QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection) const

This function overloads connect().

Connects signal from the sender object to this object's method.

Equivalent to connect(sender, signal, this, method, type).

Every connection you make emits a signal, so duplicate connections emit two signals. You can break a connection using disconnect().

Note: This function is thread-safe.

See also disconnect().

[static] template <typename PointerToMemberFunction, typename Functor> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type = Qt::AutoConnection)

This function overloads connect().

Creates a connection of a given type from signal in sender object to functor to be placed in a specific event loop of context, and returns a handle to the connection.

Note: Qt::UniqueConnections do not work for lambdas, non-member functions and functors; they only apply to connecting to member functions.

The signal must be a function declared as a signal in the header. The slot function can be any function or functor that can be connected to the signal. A slot function can be connected to a given signal if the signal has at least as many arguments as the slot function. There must exist implicit conversion between the types of the corresponding arguments in the signal and the slot.

Example:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, this, someFunction, Qt::QueuedConnection);

Lambda expressions can also be used:

QByteArray page = ...;
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost("qt-project.org", 80);
QObject::connect(socket, &QTcpSocket::connected, this, [=] () {
        socket->write("GET " + page + "\r\n");
    }, Qt::AutoConnection);

The connection will automatically disconnect if the sender or the context is destroyed. However, you should take care that any objects used within the functor are still alive when the signal is emitted.

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe.

[static] template <typename PointerToMemberFunction> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)

This function overloads connect().

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.

The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.

Example:

QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
                 label,  &QLabel::setText);

This example ensures that the label always displays the current line edit text.

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in the same order as the order the connection was made, when the signal is emitted

The function returns an handle to a connection if it successfully connects the signal to the slot. The Connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of signal (if it was not declared as a signal) You can check if the QMetaObject::Connection is valid by casting it to a bool.

By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection.

The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)

make sure to declare the argument type with Q_DECLARE_METATYPE

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe.

See also Differences between String-Based and Functor-Based Connections.

[virtual protected] void QObject::connectNotify(const QMetaMethod &signal)

This virtual function is called when something has been connected to signal in this object.

If you want to compare signal with a specific signal, you can use QMetaMethod::fromSignal() as follows:

if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
    // signal is valueChanged
}

Warning: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.

Warning: This function is called from the thread which performs the connection, which may be a different thread from the thread in which this object lives. This function may also be called with a QObject internal mutex locked. It is therefore not allowed to re-enter any QObject functions, including isSignalConnected(), from your reimplementation. If you lock a mutex in your reimplementation, make sure that you don't call QObject functions with that mutex held in other places or it will result in a deadlock.

See also connect() and disconnectNotify().

[virtual protected] void QObject::customEvent(QEvent *event)

This event handler can be reimplemented in a subclass to receive custom events. Custom events are user-defined events with a type value at least as large as the QEvent::User item of the QEvent::Type enum, and is typically a QEvent subclass. The event is passed in the event parameter.

See also event() and QEvent.

[slot] void QObject::deleteLater()

Schedules this object for deletion.

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. If deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called. This does not apply to objects deleted while a previous, nested event loop was still running: the Qt event loop will delete those objects as soon as the new nested event loop starts.

In situations where Qt is not driving the event dispatcher via e.g. QCoreApplication::exec() or QEventLoop::exec(), deferred deletes will not be processed automatically. To ensure deferred deletion in this scenario, the following workaround can be used:

const auto *eventDispatcher = QThread::currentThread()->eventDispatcher();
QObject::connect(eventDispatcher, &QAbstractEventDispatcher::aboutToBlock,
    QThread::currentThread(), []{
        if (QThread::currentThread()->loopLevel() == 0)
            QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
    }
);

Note: This function is thread-safe.

See also destroyed() and QPointer.

[signal] void QObject::destroyed(QObject *obj = nullptr)

This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.

All the objects's children are destroyed immediately after this signal is emitted.

See also deleteLater() and QPointer.

[static] bool QObject::disconnect(const QMetaObject::Connection &connection)

Disconnect a connection.

If the connection is invalid or has already been disconnected, do nothing and return false.

See also connect().

[static] bool QObject::disconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method)

Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.

This function provides the same possibilities like disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) but uses QMetaMethod to represent the signal and the method to be disconnected.

Additionally this function returns false and no signals and slots disconnected if:

  1. signal is not a member of sender class or one of its parent classes.
  2. method is not a member of receiver class or one of its parent classes.
  3. signal instance represents not a signal.

Note: Use the the same syntax, pointer-to-member-function or string-based using the SIGNAL and SLOT macros, in connect() and corresponding disconnect() calls.

To avoid mismatches, store the connection handle returned by connect(), and use it in the call to disconnect().

Note: If a queued connection is disconnected, already scheduled events may still be delivered, causing the receiver to be called after the connection is disconnected.

QMetaMethod() may be used as wildcard in the meaning "any signal" or "any slot in receiving object". In the same way nullptr can be used for receiver in the meaning "any receiving object". In this case method should also be QMetaMethod(). sender parameter should be never nullptr.

Note: Disconnecting all signal-slot connections will also disconnect the QObject::destroyed() signal if it is connected. Doing so can adversely affect classes that rely on this signal for cleaning up resources. It is recommended to disconnect only the specific signals that were connected by application code.

See also disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method).

[static] bool QObject::disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)

Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.

A signal-slot connection is removed when either of the objects involved are destroyed.

disconnect() is typically used in three ways, as the following examples demonstrate.

  1. Disconnect everything connected to an object's signals:
    disconnect(myObject, nullptr, nullptr, nullptr);

    equivalent to the non-static overloaded function

    myObject->disconnect();
  2. Disconnect everything connected to a specific signal:
    disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);

    equivalent to the non-static overloaded function

    myObject->disconnect(SIGNAL(mySignal()));
  3. Disconnect a specific receiver:
    disconnect(myObject, nullptr, myReceiver, nullptr);

    equivalent to the non-static overloaded function

    myObject->disconnect(myReceiver);

Note: Use the the same syntax, pointer-to-member-function or string-based using the SIGNAL and SLOT macros, in connect() and corresponding disconnect() calls.

To avoid mismatches, store the connection handle returned by connect(), and use it in the call to disconnect().

Note: If a queued connection is disconnected, already scheduled events may still be delivered, causing the receiver to be called after the connection is disconnected.

nullptr may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.

The sender may never be nullptr. (You cannot disconnect signals from more than one object in a single call.)

If signal is nullptr, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.

If receiver is nullptr, it disconnects anything connected to signal. If not, slots in objects other than receiver are not disconnected.

If method is nullptr, it disconnects anything that is connected to receiver. If not, only slots named method will be disconnected, and all other slots are left alone. The method must be nullptr if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.

Note: Disconnecting all signal-slot connections will also disconnect the QObject::destroyed() signal if it is connected. Doing so can adversely affect classes that rely on this signal for cleaning up resources. It is recommended to disconnect only the specific signals that were connected by application code.

Note: This function is thread-safe.

See also connect().

bool QObject::disconnect(const QObject *receiver, const char *method = nullptr) const

This function overloads disconnect().

Disconnects all signals in this object from receiver's method.

Note: Use the the same syntax, pointer-to-member-function or string-based using the SIGNAL and SLOT macros, in connect() and corresponding disconnect() calls.

To avoid mismatches, store the connection handle returned by connect(), and use it in the call to disconnect().

Note: If a queued connection is disconnected, already scheduled events may still be delivered, causing the receiver to be called after the connection is disconnected.

A signal-slot connection is removed when either of the objects involved are destroyed.

bool QObject::disconnect(const char *signal = nullptr, const QObject *receiver = nullptr, const char *method = nullptr) const

This function overloads disconnect().

Disconnects signal from method of receiver.

Note: Use the the same syntax, pointer-to-member-function or string-based using the SIGNAL and SLOT macros, in connect() and corresponding disconnect() calls.

To avoid mismatches, store the connection handle returned by connect(), and use it in the call to disconnect().

Note: If a queued connection is disconnected, already scheduled events may still be delivered, causing the receiver to be called after the connection is disconnected.

A signal-slot connection is removed when either of the objects involved are destroyed.

Note: Disconnecting all signal-slot connections will also disconnect the QObject::destroyed() signal if it is connected. Doing so can adversely affect classes that rely on this signal for cleaning up resources. It is recommended to disconnect only the specific signals that were connected by application code.

Note: This function is thread-safe.

[static] template <typename PointerToMemberFunction> bool QObject::disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)

This function overloads disconnect().

Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.

A signal-slot connection is removed when either of the objects involved are destroyed.

disconnect() is typically used in three ways, as the following examples demonstrate.

  1. Disconnect everything connected to an object's signals:
    disconnect(myObject, nullptr, nullptr, nullptr);
  2. Disconnect everything connected to a specific signal:
    disconnect(myObject, &MyObject::mySignal(), nullptr, nullptr);
  3. Disconnect a specific receiver:
    disconnect(myObject, nullptr, myReceiver, nullptr);
  4. Disconnect a connection from one specific signal to a specific slot:
    QObject::disconnect(lineEdit, &QLineEdit::textChanged,
                     label,  &QLabel::setText);

nullptr may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.

The sender may never be nullptr. (You cannot disconnect signals from more than one object in a single call.)

If signal is nullptr, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.

If receiver is nullptr, it disconnects anything connected to signal. If not, only slots in the specified receiver are disconnected. disconnect() with a non-null receiver also disconnects slot functions that were connected with receiver as their context object.

If method is nullptr, it disconnects anything that is connected to receiver. If not, only slots named method will be disconnected, and all other slots are left alone. The method must be nullptr if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.

Note: It is not possible to use this overload to disconnect signals connected to functors or lambda expressions. That is because it is not possible to compare them. Instead, use the overload that takes a QMetaObject::Connection.

Note: Unless method is nullptr, this function will also not break connections that were made using the string-based version of connect(). To break such connections, use the corresponding string-based overload of disconnect().

Note: This function is thread-safe.

See also connect().

[virtual protected] void QObject::disconnectNotify(const QMetaMethod &signal)

This virtual function is called when something has been disconnected from signal in this object.

See connectNotify() for an example of how to compare signal with a specific signal.

If all signals were disconnected from this object (e.g., the signal argument to disconnect() was nullptr), disconnectNotify() is only called once, and the signal will be an invalid QMetaMethod (QMetaMethod::isValid() returns false).

Warning: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.

Warning: This function is called from the thread which performs the disconnection, which may be a different thread from the thread in which this object lives. This function may also be called with a QObject internal mutex locked. It is therefore not allowed to re-enter any QObject functions, including isSignalConnected(), from your reimplementation. If you lock a mutex in your reimplementation, make sure that you don't call QObject functions with that mutex held in other places or it will result in a deadlock.

See also disconnect() and connectNotify().

void QObject::dumpObjectInfo() const

Dumps information about signal connections, etc. for this object to the debug output.

Note: Before Qt 5.9, this function was not const.

See also dumpObjectTree().

void QObject::dumpObjectTree() const

Dumps a tree of children to the debug output.

Note: Before Qt 5.9, this function was not const.

See also dumpObjectInfo().

QList<QByteArray> QObject::dynamicPropertyNames() const

Returns the names of all properties that were dynamically added to the object using setProperty().

[virtual] bool QObject::event(QEvent *e)

This virtual function receives events to an object and should return true if the event e was recognized and processed.

The event() function can be reimplemented to customize the behavior of an object.

Make sure you call the parent event class implementation for all the events you did not handle.

Example:

class MyClass : public QWidget
{
    Q_OBJECT

public:
    MyClass(QWidget *parent = nullptr);
    ~MyClass();

    bool event(QEvent* ev) override
    {
        if (ev->type() == QEvent::PolishRequest) {
            // overwrite handling of PolishRequest if any
            doThings();
            return true;
        } else  if (ev->type() == QEvent::Show) {
            // complement handling of Show if any
            doThings2();
            QWidget::event(ev);
            return true;
        }
        // Make sure the rest of events are handled
        return QWidget::event(ev);
    }
};

See also installEventFilter(), timerEvent(), QCoreApplication::sendEvent(), and QCoreApplication::postEvent().

[virtual] bool QObject::eventFilter(QObject *watched, QEvent *event)

Filters events if this object has been installed as an event filter for the watched object.

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

Example:

class MainWindow : public QMainWindow
{
public:
    MainWindow();

protected:
    bool eventFilter(QObject *obj, QEvent *ev) override;

private:
    QTextEdit *textEdit;
};

MainWindow::MainWindow()
{
    textEdit = new QTextEdit;
    setCentralWidget(textEdit);

    textEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == textEdit) {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
            qDebug() << "Ate key press" << keyEvent->key();
            return true;
        } else {
            return false;
        }
    } else {
        // pass the event on to the parent class
        return QMainWindow::eventFilter(obj, event);
    }
}

Notice in the example above that unhandled events are passed to the base class's eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.

Some events, such as QEvent::ShortcutOverride must be explicitly accepted (by calling accept() on them) in order to prevent propagation.

Warning: If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.

See also installEventFilter().

template <typename T> T QObject::findChild(QAnyStringView name, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

Returns the child of this object that can be cast into type T and that is called name, or nullptr if there is no such object. A null name argument causes all objects to be matched. An empty, non-null name matches only objects whose objectName is empty. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

If there is more than one child matching the search, the most-direct ancestor is returned. If there are several most-direct ancestors, the first child in children() will be returned. In that case, it's better to use findChildren() to get the complete list of all children.

This example returns a child QPushButton of parentWidget named "button1", even if the button isn't a direct child of the parent:

QPushButton *button = parentWidget->findChild<QPushButton *>("button1");

This example returns a QListWidget child of parentWidget:

QListWidget *list = parentWidget->findChild<QListWidget *>();

This example returns a child QPushButton of parentWidget (its direct parent) named "button1":

QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly);

This example returns a QListWidget child of parentWidget, its direct parent:

QListWidget *list = parentWidget->findChild<QListWidget *>(Qt::FindDirectChildrenOnly);

Note: In Qt versions prior to 6.7, this function took name as QString, not QAnyStringView.

See also findChildren().

[since 6.7] template <typename T> T QObject::findChild(Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

This is an overloaded function.

Returns the child of this object that can be cast into type T, or nullptr if there is no such object. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

If there is more than one child matching the search, the most-direct ancestor is returned. If there are several most-direct ancestors, the first child in children() will be returned. In that case, it's better to use findChildren() to get the complete list of all children.

This function was introduced in Qt 6.7.

See also findChildren().

template <typename T> QList<T> QObject::findChildren(QAnyStringView name, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. A null name argument causes all objects to be matched, an empty one only those whose objectName is empty. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

The following example shows how to find a list of child QWidgets of the specified parentWidget named widgetname:

QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");

This example returns all QPushButtons that are children of parentWidget:

QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();

This example returns all QPushButtons that are immediate children of parentWidget:

QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(Qt::FindDirectChildrenOnly);

Note: In Qt versions prior to 6.7, this function took name as QString, not QAnyStringView.

See also findChild().

[since 6.3] template <typename T> QList<T> QObject::findChildren(Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

This is an overloaded function.

Returns all children of this object that can be cast to type T, or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

This function was introduced in Qt 6.3.

See also findChild().

template <typename T> QList<T> QObject::findChildren(const QRegularExpression &re, Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

This function overloads findChildren().

Returns the children of this object that can be cast to type T and that have names matching the regular expression re, or an empty list if there are no such objects. The search is performed recursively, unless options specifies the option FindDirectChildrenOnly.

bool QObject::inherits(const char *className) const

Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.

A class is considered to inherit itself.

Example:

QTimer *timer = new QTimer;         // QTimer inherits QObject
timer->inherits("QTimer");          // returns true
timer->inherits("QObject");         // returns true
timer->inherits("QAbstractButton"); // returns false

// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject");        // returns true
layout->inherits("QLayoutItem");    // returns true (even though QLayoutItem is not a QObject)

If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.

See also metaObject() and qobject_cast().

void QObject::installEventFilter(QObject *filterObj)

Installs an event filter filterObj on this object. For example:

monitoredObj->installEventFilter(filterObj);

An event filter is an object that receives all events that are sent to this object. The filter can either stop the event or forward it to this object. The event filter filterObj receives events via its eventFilter() function. The eventFilter() function must return true if the event should be filtered, (i.e. stopped); otherwise it must return false.

If multiple event filters are installed on a single object, the filter that was installed last is activated first.

If filterObj has already been installed for this object, this function moves it so it acts as if it was installed last.

Here's a KeyPressEater class that eats the key presses of its monitored objects:

class KeyPressEater : public QObject
{
    Q_OBJECT
    ...

protected:
    bool eventFilter(QObject *obj, QEvent *event) override;
};

bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        qDebug("Ate key press %d", keyEvent->key());
        return true;
    } else {
        // standard event processing
        return QObject::eventFilter(obj, event);
    }
}

And here's how to install it on two widgets:

KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
QListView *listView = new QListView(this);

pushButton->installEventFilter(keyPressEater);
listView->installEventFilter(keyPressEater);

The QShortcut class, for example, uses this technique to intercept shortcut key presses.

Warning: If you delete the receiver object in your eventFilter() function, be sure to return true. If you return false, Qt sends the event to the deleted object and the program will crash.

Note that the filtering object must be in the same thread as this object. If filterObj is in a different thread, this function does nothing. If either filterObj or this object are moved to a different thread after calling this function, the event filter will not be called until both objects have the same thread affinity again (it is not removed).

See also removeEventFilter(), eventFilter(), and event().

[since 6.4] bool QObject::isQuickItemType() const

Returns true if the object is a QQuickItem; otherwise returns false.

Calling this function is equivalent to calling inherits("QQuickItem"), except that it is much faster.

This function was introduced in Qt 6.4.

[protected] bool QObject::isSignalConnected(const QMetaMethod &signal) const

Returns true if the signal is connected to at least one receiver, otherwise returns false.

signal must be a signal member of this object, otherwise the behaviour is undefined.

static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
if (isSignalConnected(valueChangedSignal)) {
    QByteArray data;
    data = get_the_value();       // expensive operation
    emit valueChanged(data);
}

As the code snippet above illustrates, you can use this function to avoid expensive initialization or emitting a signal that nobody listens to. However, in a multithreaded application, connections might change after this function returns and before the signal gets emitted.

Warning: This function violates the object-oriented principle of modularity. In particular, this function must not be called from an override of connectNotify() or disconnectNotify(), as those might get called from any thread.

bool QObject::isWidgetType() const

Returns true if the object is a widget; otherwise returns false.

Calling this function is equivalent to calling inherits("QWidget"), except that it is much faster.

bool QObject::isWindowType() const

Returns true if the object is a window; otherwise returns false.

Calling this function is equivalent to calling inherits("QWindow"), except that it is much faster.

void QObject::killTimer(int id)

Kills the timer with timer identifier, id.

The timer identifier is returned by startTimer() when a timer event is started.

See also timerEvent() and startTimer().

[since 6.8] void QObject::killTimer(Qt::TimerId id)

This is an overloaded function.

This function was introduced in Qt 6.8.

[virtual] const QMetaObject *QObject::metaObject() const

Returns a pointer to the meta-object of this object.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have no pointer to an actual object instance but still want to access the meta-object of a class, you can use staticMetaObject.

Example:

QObject *obj = new QPushButton;
obj->metaObject()->className();             // returns "QPushButton"

QPushButton::staticMetaObject.className();  // returns "QPushButton"

See also staticMetaObject.

bool QObject::moveToThread(QThread *targetThread)

Changes the thread affinity for this object and its children and returns true on success. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives. For example:

myObject->moveToThread(QApplication::instance()->thread());

If targetThread is nullptr, all event processing for this object and its children stops, as they are no longer associated with any thread.

Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread, provided it is not nullptr: when it is nullptr, no event processing for this object or its children can happen, as they are no longer associated with any thread.

Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread. There is one exception to this rule however: objects with no thread affinity can be "pulled" to the current thread.

See also thread().

[private signal] void QObject::objectNameChanged(const QString &objectName)

This signal is emitted after the object's name has been changed. The new object name is passed as objectName.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

Note: Notifier signal for property objectName.

See also QObject::objectName.

QObject *QObject::parent() const

Returns a pointer to the parent object.

See also setParent() and children().

QVariant QObject::property(const char *name) const

Returns the value of the object's name property.

If no such property exists, the returned variant is invalid.

Information about all available properties is provided through the metaObject() and dynamicPropertyNames().

See also setProperty(), QVariant::isValid(), metaObject(), and dynamicPropertyNames().

[protected] int QObject::receivers(const char *signal) const

Returns the number of receivers connected to the signal.

Since both slots and signals can be used as receivers for signals, and the same connections can be made many times, the number of receivers is the same as the number of connections made from this signal.

When calling this function, you can use the SIGNAL() macro to pass a specific signal:

if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
    QByteArray data;
    get_the_value(&data);       // expensive operation
    emit valueChanged(data);
}

Warning: This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.

See also isSignalConnected().

void QObject::removeEventFilter(QObject *obj)

Removes an event filter object obj from this object. The request is ignored if such an event filter has not been installed.

All event filters for this object are automatically removed when this object is destroyed.

It is always safe to remove an event filter, even during event filter activation (i.e. from the eventFilter() function).

See also installEventFilter(), eventFilter(), and event().

[protected] QObject *QObject::sender() const

Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns nullptr. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.

The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal.

Warning: This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.

Warning: As mentioned above, the return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

See also senderSignalIndex().

[protected] int QObject::senderSignalIndex() const

Returns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender(). If called outside of a slot activated by a signal, -1 is returned.

For signals with default parameters, this function will always return the index with all parameters, regardless of which was used with connect(). For example, the signal destroyed(QObject *obj = \nullptr) will have two different indexes (with and without the parameter), but this function will always return the index with a parameter. This does not apply when overloading signals with different parameters.

Warning: This function violates the object-oriented principle of modularity. However, getting access to the signal index might be useful when many signals are connected to a single slot.

Warning: The return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

See also sender(), QMetaObject::indexOfSignal(), and QMetaObject::method().

void QObject::setObjectName(const QString &name)

Sets the object's name to name.

Note: Setter function for property objectName.

See also objectName().

[since 6.4] void QObject::setObjectName(QAnyStringView name)

This is an overloaded function.

Note: Setter function for property objectName.

This function was introduced in Qt 6.4.

void QObject::setParent(QObject *parent)

Makes the object a child of parent.

See also parent() and children().

bool QObject::setProperty(const char *name, const QVariant &value)

Sets the value of the object's name property to value.

If the property is defined in the class using Q_PROPERTY then true is returned on success and false otherwise. If the property is not defined using Q_PROPERTY, and therefore not listed in the meta-object, it is added as a dynamic property and false is returned.

Information about all available properties is provided through the metaObject() and dynamicPropertyNames().

Dynamic properties can be queried again using property() and can be removed by setting the property value to an invalid QVariant. Changing the value of a dynamic property causes a QDynamicPropertyChangeEvent to be sent to the object.

Note: Dynamic properties starting with "_q_" are reserved for internal purposes.

See also property(), metaObject(), dynamicPropertyNames(), and QMetaProperty::write().

[since 6.6] bool QObject::setProperty(const char *name, QVariant &&value)

This function overloads setProperty.

This function was introduced in Qt 6.6.

[noexcept] bool QObject::signalsBlocked() const

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

See also blockSignals() and QSignalBlocker.

int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)

This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds. This is equivalent to calling:

startTimer(std::chrono::milliseconds{interval}, timerType);

See also timerEvent(), killTimer(), QChronoTimer, and QBasicTimer.

int QObject::startTimer(std::chrono::nanoseconds interval, Qt::TimerType timerType = Qt::CoarseTimer)

This is an overloaded function.

Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.

A timer event will occur every interval until killTimer() is called. If interval is equal to std::chrono::duration::zero(), then the timer event occurs once every time there are no more window system events to process.

The virtual timerEvent() function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.

If multiple timers are running, the QTimerEvent::id() method can be used to find out which timer was activated.

Example:

class MyObject : public QObject
{
    Q_OBJECT

public:
    MyObject(QObject *parent = nullptr);

protected:
    void timerEvent(QTimerEvent *event) override;
};

MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
    using namespace std::chrono_literals;

    startTimer(50ms);
    startTimer(5s);
    startTimer(10min);
    startTimer(1h);
}

void MyObject::timerEvent(QTimerEvent *event)
{
    qDebug() << "Timer ID:" << event->id();
}

Note that the accuracy of the timer depends on the underlying operating system and hardware.

The timerType argument allows you to customize the accuracy of the timer. See Qt::TimerType for information on the different timer types. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

The QTimer and QChronoTimer classes provide a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QChronoTimer but less clumsy than using timer IDs directly.

Note: Starting from Qt 6.8 the type of interval is std::chrono::nanoseconds, prior to that it was std::chrono::milliseconds. This change is backwards compatible with older releases of Qt.

Note: In Qt 6.8, QObject was changed to use Qt::TimerId to represent timer IDs. This method converts the TimerId to int for backwards compatibility reasons, however you can use Qt::TimerId to check the value returned by this method, for example:

    QObject *obj;
    ...
    const auto id = Qt::TimerId{obj->startTimer(100ms)};
    if (id != Qt::TimerId::Invalid)
        // The timer has been started successfully

See also timerEvent(), killTimer(), QChronoTimer, and QBasicTimer.

QThread *QObject::thread() const

Returns the thread in which the object lives.

See also moveToThread().

[virtual protected] void QObject::timerEvent(QTimerEvent *event)

This event handler can be reimplemented in a subclass to receive timer events for the object.

QChronoTimer provides higher-level interfaces to the timer functionality, and also more general information about timers. The timer event is passed in the event parameter.

See also startTimer(), killTimer(), and event().

[static] QString QObject::tr(const char *sourceText, const char *disambiguation = nullptr, int n = -1)

Returns a translated version of sourceText, optionally based on a disambiguation string and value of n for strings containing plurals; otherwise returns QString::fromUtf8(sourceText) if no appropriate translated string is available.

Example:

void SpreadSheet::setupMenuBar()
{
    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
    ...

If the same sourceText is used in different roles within the same context, an additional identifying string may be passed in disambiguation (nullptr by default).

Example:

MyWindow::MyWindow()
{
    QLabel *senderLabel = new QLabel(tr("Name:"));
    QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
    ...

See Writing Source Code for Translation for a detailed description of Qt's translation mechanisms in general, and the Disambiguate Identical Text section for information on disambiguation.

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

See also QCoreApplication::translate() and Internationalization with Qt.

Member Variable Documentation

const QMetaObject QObject::staticMetaObject

This variable stores the meta-object for the class.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every class that contains the Q_OBJECT macro will also have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have a pointer to an object, you can use metaObject() to retrieve the meta-object associated with that object.

Example:

QPushButton::staticMetaObject.className();  // returns "QPushButton"

QObject *obj = new QPushButton;
obj->metaObject()->className();             // returns "QPushButton"

See also metaObject().

Related Non-Members

template <typename T> T qobject_cast(QObject *object)

template <typename T> T qobject_cast(const QObject *object)

Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns nullptr. If object is nullptr then it will also return nullptr.

The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.

A class is considered to inherit itself.

Example:

QObject *obj = new QTimer;          // QTimer inherits QObject

QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj

QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == nullptr

The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.

qobject_cast() can also be used in conjunction with interfaces.

Warning: If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.

See also QObject::inherits().

QObjectList

Synonym for QList<QObject *>.

Macro Documentation

[since 6.7] QT_NO_CONTEXTLESS_CONNECT

Defining this macro will disable the overload of QObject::connect() that connects a signal to a functor, without also specifying a QObject as a receiver/context object (that is, the 3-arguments overload of QObject::connect()).

Using the context-less overload is error prone, because it is easy to connect to functors that depend on some local state of the receiving end. If such local state gets destroyed, the connection does not get automatically disconnected.

Moreover, such connections are always direct connections, which may cause issues in multithreaded scenarios (for instance, if the signal is emitted from another thread).

This macro was introduced in Qt 6.7.

See also QObject::connect and Qt::ConnectionType.

QT_NO_NARROWING_CONVERSIONS_IN_CONNECT

Defining this macro will disable narrowing and floating-point-to-integral conversions between the arguments carried by a signal and the arguments accepted by a slot, when the signal and the slot are connected using the PMF-based syntax.

See also QObject::connect.

Q_CLASSINFO(Name, Value)

This macro associates extra information to the class, which is available using QObject::metaObject(). The extra information takes the form of a Name string and a Value literal string.

Example:

class MyClass : public QObject
{
    Q_OBJECT
    Q_CLASSINFO("Author", "Pierre Gendron")
    Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")

public:
    ...
};

Qt makes use of the macro in Qt D-Bus and Qt Qml modules. For instance, when defining QML Object Types in C++, you can designate a property as the default one:

Q_CLASSINFO("DefaultProperty", "content")

See also QMetaObject::classInfo(), Using Qt D-Bus Adaptors, and Defining QML Types from C++.

Q_EMIT

Use this macro to replace the emit keyword for emitting signals, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

Q_ENUM(...)

This macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a class that has the Q_OBJECT, Q_GADGET or Q_GADGET_EXPORT macro. For namespaces use Q_ENUM_NS() instead.

For example:

class MyClass : public QObject
{
    Q_OBJECT

public:
    MyClass(QObject *parent = nullptr);
    ~MyClass();

    enum Priority { High, Low, VeryHigh, VeryLow };
    Q_ENUM(Priority)
    void setPriority(Priority priority);
    Priority priority() const;
};

Enumerations that are declared with Q_ENUM have their QMetaEnum registered in the enclosing QMetaObject. You can also use QMetaEnum::fromType() to get the QMetaEnum.

Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE(). This will enable useful features; for example, if used in a QVariant, you can convert them to strings. Likewise, passing them to QDebug will print out their names.

Mind that the enum values are stored as signed int in the meta object system. Registering enumerations with values outside the range of values valid for int will lead to overflows and potentially undefined behavior when accessing them through the meta object system. QML, for example, does access registered enumerations through the meta object system.

See also Qt's Property System.

Q_ENUM_NS(...)

This macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a namespace that has the Q_NAMESPACE macro. It is the same as Q_ENUM but in a namespace.

Enumerations that are declared with Q_ENUM_NS have their QMetaEnum registered in the enclosing QMetaObject. You can also use QMetaEnum::fromType() to get the QMetaEnum.

Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE(). This will enable useful features; for example, if used in a QVariant, you can convert them to strings. Likewise, passing them to QDebug will print out their names.

Mind that the enum values are stored as signed int in the meta object system. Registering enumerations with values outside the range of values valid for int will lead to overflows and potentially undefined behavior when accessing them through the meta object system. QML, for example, does access registered enumerations through the meta object system.

See also Qt's Property System.

Q_FLAG(...)

This macro registers a single flags type with the meta-object system. It is typically used in a class definition to declare that values of a given enum can be used as flags and combined using the bitwise OR operator. For namespaces use Q_FLAG_NS() instead.

The macro must be placed after the enum declaration. The declaration of the flags type is done using the Q_DECLARE_FLAGS() macro.

For example, in QItemSelectionModel, the SelectionFlags flag is declared in the following way:

class QItemSelectionModel : public QObject
{
    Q_OBJECT

public:
    ...
    enum SelectionFlag {
        NoUpdate       = 0x0000,
        Clear          = 0x0001,
        Select         = 0x0002,
        Deselect       = 0x0004,
        Toggle         = 0x0008,
        Current        = 0x0010,
        Rows           = 0x0020,
        Columns        = 0x0040,
        SelectCurrent  = Select | Current,
        ToggleCurrent  = Toggle | Current,
        ClearAndSelect = Clear | Select
    };

    Q_DECLARE_FLAGS(SelectionFlags, SelectionFlag)
    Q_FLAG(SelectionFlags)
    ...
}

Note: The Q_FLAG macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUM() in addition to this macro.

See also Qt's Property System.

Q_FLAG_NS(...)

This macro registers a single flags type with the meta-object system. It is used in a namespace that has the Q_NAMESPACE macro, to declare that values of a given enum can be used as flags and combined using the bitwise OR operator. It is the same as Q_FLAG but in a namespace.

The macro must be placed after the enum declaration.

Note: The Q_FLAG_NS macro takes care of registering individual flag values with the meta-object system, so it is unnecessary to use Q_ENUM_NS() in addition to this macro.

See also Qt's Property System.

Q_GADGET

The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject but still want to use some of the reflection capabilities offered by QMetaObject.

Note: This macro expansion ends with a private: access specifier. If you declare members immediately after this macro, those members will also be private. To add public (or protected) members right after the macro, use a public: (or protected:) access specifier.

Q_GADGETs can have Q_ENUM, Q_PROPERTY and Q_INVOKABLE, but they cannot have signals or slots.

Q_GADGET makes a class member, staticMetaObject, available. staticMetaObject is of type QMetaObject and provides access to the enums declared with Q_ENUM.

See also Q_GADGET_EXPORT.

[since 6.3] Q_GADGET_EXPORT(EXPORT_MACRO)

The Q_GADGET_EXPORT macro works exactly like the Q_GADGET macro. However, the staticMetaObject variable that is made available (see Q_GADGET) is declared with the supplied EXPORT_MACRO qualifier. This is useful if the object needs to be exported from a dynamic library, but the enclosing class as a whole should not be (e.g. because it consists of mostly inline functions).

Note: This macro expansion ends with a private: access specifier. If you declare members immediately after this macro, those members will also be private. To add public (or protected) members right after the macro, use a public: (or protected:) access specifier.

For example:

class Point {
    Q_GADGET_EXPORT(EXPORT_MACRO)
    Q_PROPERTY(int x MEMBER x)
    Q_PROPERTY(int y MEMBER y)
    ~~~

This macro was introduced in Qt 6.3.

See also Q_GADGET and Creating Shared Libraries.

Q_INTERFACES(...)

This macro tells Qt which interfaces the class implements. This is used when implementing plugins.

See also Q_DECLARE_INTERFACE(), Q_PLUGIN_METADATA(), and How to Create Qt Plugins.

Q_INVOKABLE

Apply this macro to declarations of member functions to allow them to be invoked via the meta-object system. The macro is written before the return type, as shown in the following example:

class Window : public QWidget
{
    Q_OBJECT

public:
    Window();
    void normalMethod();
    Q_INVOKABLE void invokableMethod();
};

The invokableMethod() function is marked up using Q_INVOKABLE, causing it to be registered with the meta-object system and enabling it to be invoked using QMetaObject::invokeMethod(). Since normalMethod() function is not registered in this way, it cannot be invoked using QMetaObject::invokeMethod().

If an invokable member function returns a pointer to a QObject or a subclass of QObject and it is invoked from QML, special ownership rules apply. See Data Type Conversion Between QML and C++ for more information.

[since 6.0] Q_MOC_INCLUDE

The Q_MOC_INCLUDE macro can be used within or outside a class, and tell the Meta Object Compiler to add an include.

// Put this in your code and the generated code will include this header.
Q_MOC_INCLUDE("myheader.h")

This is useful if the types you use as properties or signal/slots arguments are forward declared.

This macro was introduced in Qt 6.0.

Q_NAMESPACE

The Q_NAMESPACE macro can be used to add QMetaObject capabilities to a namespace.

Q_NAMESPACEs can have Q_CLASSINFO, Q_ENUM_NS, Q_FLAG_NS, but they cannot have Q_ENUM, Q_FLAG, Q_PROPERTY, Q_INVOKABLE, signals nor slots.

Q_NAMESPACE makes an external variable, staticMetaObject, available. staticMetaObject is of type QMetaObject and provides access to the enums declared with Q_ENUM_NS/Q_FLAG_NS.

For example:

namespace test {
Q_NAMESPACE
...

See also Q_NAMESPACE_EXPORT.

Q_NAMESPACE_EXPORT(EXPORT_MACRO)

The Q_NAMESPACE_EXPORT macro can be used to add QMetaObject capabilities to a namespace.

It works exactly like the Q_NAMESPACE macro. However, the external staticMetaObject variable that gets defined in the namespace is declared with the supplied EXPORT_MACRO qualifier. This is useful if the object needs to be exported from a dynamic library.

For example:

namespace test {
Q_NAMESPACE_EXPORT(EXPORT_MACRO)
...

See also Q_NAMESPACE and Creating Shared Libraries.

Q_OBJECT

The Q_OBJECT macro is used to enable meta-object features, such as dynamic properties, signals, and slots.

You can add the Q_OBJECT macro to any section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system.

Note: This macro expansion ends with a private: access specifier. If you declare members immediately after this macro, those members will also be private. To add public (or protected) members right after the macro, use a public: (or protected:) access specifier.

Example:

#include <QObject>

class Counter : public QObject
{
    Q_OBJECT

// Note. The Q_OBJECT macro starts a private section.
// To declare public members, use the 'public:' access modifier.
public:
    Counter() { m_value = 0; }

    int value() const { return m_value; }

public slots:
    void setValue(int value);

signals:
    void valueChanged(int newValue);

private:
    int m_value;
};

Note: This macro requires the class to be a subclass of QObject. Use Q_GADGET or Q_GADGET_EXPORT instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not a QObject subclass.

See also Meta-Object System, Signals and Slots, and Qt's Property System.

Q_PROPERTY(...)

This macro is used for declaring properties in classes that inherit QObject. Properties behave like class data members, but they have additional features accessible through the Meta-Object System.

Q_PROPERTY(type name
           (READ getFunction [WRITE setFunction] |
            MEMBER memberName [(READ getFunction | WRITE setFunction)])
           [RESET resetFunction]
           [NOTIFY notifySignal]
           [REVISION int | REVISION(int[, int])]
           [DESIGNABLE bool]
           [SCRIPTABLE bool]
           [STORED bool]
           [USER bool]
           [BINDABLE bindableProperty]
           [CONSTANT]
           [FINAL]
           [REQUIRED])

The property name and type and the READ function are required. The type can be any type supported by QVariant, or it can be a user-defined type. The other items are optional, but a WRITE function is common. The attributes default to true except USER, which defaults to false.

For example:

Q_PROPERTY(QString title READ title WRITE setTitle USER true)

For more details about how to use this macro, and a more detailed example of its use, see the discussion on Qt's Property System.

See also Qt's Property System.

Q_REVISION

Apply this macro to declarations of member functions to tag them with a revision number in the meta-object system. The macro is written before the return type, as shown in the following example:

class Window : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(int normalProperty READ normalProperty)
    Q_PROPERTY(int newProperty READ newProperty REVISION(2, 1))

public:
    Window();
    int normalProperty();
    int newProperty();
public slots:
    void normalMethod();
    Q_REVISION(2, 1) void newMethod();
};

This is useful when using the meta-object system to dynamically expose objects to another API, as you can match the version expected by multiple versions of the other API. Consider the following simplified example:

    Window window;
    int expectedRevision = 0;
    const QMetaObject *windowMetaObject = window.metaObject();
    for (int i=0; i < windowMetaObject->methodCount(); i++)
        if (windowMetaObject->method(i).revision() <= expectedRevision)
            exposeMethod(windowMetaObject->method(i));
    for (int i=0; i < windowMetaObject->propertyCount(); i++)
        if (windowMetaObject->property(i).revision() <= expectedRevision)
            exposeProperty(windowMetaObject->property(i));

Using the same Window class as the previous example, the newProperty and newMethod would only be exposed in this code when the expected version is 2.1 or greater.

Since all methods are considered to be in revision 0 if untagged, a tag of Q_REVISION(0) or Q_REVISION(0, 0) is invalid and ignored.

You can pass one or two integer parameters to Q_REVISION. If you pass one parameter, it denotes the minor version only. This means that the major version is unspecified. If you pass two, the first parameter is the major version and the second parameter is the minor version.

This tag is not used by the meta-object system itself. Currently this is only used by the QtQml module.

For a more generic string tag, see QMetaMethod::tag()

See also QMetaMethod::revision().

Q_SET_OBJECT_NAME(Object)

This macro assigns Object the objectName "Object".

It doesn't matter whether Object is a pointer or not, the macro figures that out by itself.

See also QObject::objectName().

Q_SIGNAL

This is an additional macro that allows you to mark a single function as a signal. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a signals or Q_SIGNALS groups.

Use this macro to replace the signals keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

Q_SIGNALS

Use this macro to replace the signals keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

Q_SLOT

This is an additional macro that allows you to mark a single function as a slot. It can be quite useful, especially when you use a 3rd-party source code parser which doesn't understand a slots or Q_SLOTS groups.

Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

Q_SLOTS

Use this macro to replace the slots keyword in class declarations, when you want to use Qt Signals and Slots with a 3rd party signal/slot mechanism.

The macro is normally used when no_keywords is specified with the CONFIG variable in the .pro file, but it can be used even when no_keywords is not specified.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.