6.0.0-rc4Source

QObject Class

The QObject class is the base class of all Nt objects that use signals and slots. More…

Header#include <QObject>
CMaketarget_link_libraries(app PRIVATE Nt::Core)
ModuleNt Core C++ Classes
Inherited byQAbstractAnimation, QAbstractAxis, QAbstractEventDispatcher, QAbstractHttpServer, QAbstractItemDelegate, QAbstractItemModel, QAbstractSeries, QAction, QActionGroup, QBarSet, QButtonGroup, QChart, QChronoTimer, QCompleter, QCoreApplication, QDBusAbstractAdaptor, QDBusAbstractInterface, QDBusPendingCallWatcher, QDBusServer, QDBusServiceWatcher, QDBusVirtualObject, QEventLoop, QFileSelector, QFileSystemWatcher, QFutureWatcherBase, QGpioLine, QIODevice, QItemSelectionModel, QJSEngine, QLayout, QLegend, QLibrary, QLocalServer, QMaskGenerator, QMimeData, QNetworkAccessManager, QObjectCleanupHandler, QOffscreenSurface, QOpenGLContext, QPieSlice, QQmlComponent, QQmlContext, QScreen, QSettings, QSharedMemory, QSignalMapper, QSignalSpy, QSocketNotifier, QSqlDriver, QStyle, QStyleHints, QSvgRenderer, QTcpServer, QTestEventLoop, QTextDocument, QThread, QThreadPool, QTimeLine, QTimer, QTranslator, QWebSocket, QWebSocketServer, QWidget, QWindow, QtFM::Engine, QtFM::FmChip, QtFM::FmEngine, QtFM::FmMusic, QtFM::FmPatch, QtFM::FmPatchValue, QtFM::FmSequence, QtFM::FmSound, QtFM::FmSoundBank, QtFM::MidiPlayer

List of all members, including inherited members

Public Functions

QObject(QObject *parent = nullptr)
virtual ~QObject()
virtual const QMetaObject *metaObject() const
boolinherits(const char *className) const
QVariantproperty(const char *name) const
boolsetProperty(const char *name, const QVariant &value)
QList<QByteArray>dynamicPropertyNames() const
QObject *parent() const
voidsetParent(QObject *parent)
const QObjectList &children() const
QStringobjectName() const
voidsetObjectName(const QString &name)
boolisWidgetType() const
boolisWindowType() const
boolisQuickItemType() const
voiddumpObjectTree() const
voiddumpObjectInfo() const
TfindChild(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
QList<T>findChildren(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const
boolsignalsBlocked() const
boolblockSignals(bool block)
QThread *thread() const
voidmoveToThread(QThread *targetThread)
intstartTimer(int intervalMs)
intstartTimer(std::chrono::milliseconds interval)
voidkillTimer(int id)
QObject *sender() const
virtual boolevent(QEvent *event)
virtual booleventFilter(QObject *watched, QEvent *event)
voidinstallEventFilter(QObject *filterObj)
voidremoveEventFilter(QObject *obj)
QMetaObject::Connectionconnect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection) const
booldisconnect(const char *signal = nullptr, const QObject *receiver = nullptr, const char *member = nullptr) const
booldisconnect(const QObject *receiver, const char *member = nullptr) const

Public Slots

voiddeleteLater()

Signals

voiddestroyed(QObject *obj = nullptr)
voidobjectNameChanged(const QString &objectName)

Static Public Members

QMetaObject::Connectionconnect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), const RecvT *receiver, Func &&slot, Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connectionconnect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), Func &&slot, Qt::ConnectionType type = Qt::AutoConnection)
booldisconnect(const QMetaObject::Connection &connection)
booldisconnect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), const QObject *receiver = nullptr, std::nullptr_t = nullptr)
QMetaObject::Connectionconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType type = Qt::AutoConnection)
QMetaObject::Connectionconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)
booldisconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
booldisconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method)

Protected Functions

virtual voidtimerEvent(QTimerEvent *event)
virtual voidchildEvent(QChildEvent *event)
virtual voidcustomEvent(QEvent *event)
virtual voidconnectNotify(const QMetaMethod &signal)
virtual voiddisconnectNotify(const QMetaMethod &signal)
intsenderSignalIndex() const
intreceivers(const char *signal) const
boolisSignalConnected(const QMetaMethod &signal) const
voidemitSignal(void (Obj::*signal)(Args...), const std::decay_t<Args> &...args)

Detailed Description

QObject provides the object tree (parent and children), signals and slots connected with connect(), per-object timers and event delivery. Deleting a parent deletes its children, and destroying an object removes every connection involving it.

Classes that declare signals must contain the Q_OBJECT macro; the ntmoc tool generates their bodies. See Signals and Slots for an overview.

The Q_OBJECT macro also declares static QString tr(const char *sourceText, const char *disambiguation = nullptr, int n = -1), which returns the translation of sourceText from the translators installed with QCoreApplication::installTranslator(), using the class name as the context.

QObject parent;
auto *child = new QObject(&parent);
child->setObjectName("worker");
Q_ASSERT(parent.findChild<QObject *>("worker") == child);

See also QPointer, QTimer, QCoreApplication, QThread and Signals and Slots.

Differences from Qt

Qt::UniqueConnection does not detect duplicate functor slots. A queued invocation that has not run yet is discarded if its connection is disconnected, where Qt still runs it. A Qt::BlockingQueuedConnection to a receiver in the emitting thread calls the slot directly, where Qt reports a deadlock. QObject does not warn when an object is deleted from a thread other than its own. Connection lists are guarded by one process-wide lock, which is held while arguments are copied for queued delivery but never while a slot or a functor runs. Signal bodies are generated by ntmoc and emit through emitSignal(). qobject_cast() is a wrapper around dynamic_cast. The meta-object of a class exists only if ntmoc processed the class; metaObject() of any other class returns that of its nearest registered base class, which is QObject::staticMetaObject at the least. There is no qt_metacast(), and no bindable properties. disconnectNotify() is not called for connections removed because an object is destroyed, and isQuickItemType() always returns false. property() and setProperty() cover the static properties that Q_PROPERTY() declares and dynamic properties, and send a QDynamicPropertyChangeEvent when a dynamic property changes; they are not thread-safe, so call them from the thread that the object lives in.

Member Function Documentation

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

Constructs an object with the given parent. The parent takes ownership and deletes the object when it is destroyed.

See also setParent().

[virtual] QObject::~QObject()

Destroys the object, emitting destroyed() first. Every connection to or from the object is removed, its timers are stopped, its pending posted events are discarded, and its children are deleted.

bool QObject::blockSignals(bool block)

If block is true, signals emitted by this object are blocked and no connected slot is called. If block is false, blocking is lifted. Returns the previous value of signalsBlocked().

Note: Unlike in Qt, destroyed() is also suppressed while signals are blocked.

See also signalsBlocked() and QSignalBlocker.

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

Called when a child is added to or removed from this object, with the details in event. A ChildAdded event arrives while the child is still being constructed, and a ChildRemoved event for a destroyed child while it is being destroyed, so use only the QObject part of QChildEvent::child() then. The base implementation does nothing.

See also setParent() and event().

const QObjectList & QObject::children() const

Returns the list of child objects, in the order they were added.

See also parent() and findChildren().

template <typename SenderT, typename SignalClass, typename... SArgs, typename RecvT, typename Func>[static] QMetaObject::Connection QObject::connect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), const RecvT *receiver, Func &&slot, Qt::ConnectionType type = Qt::AutoConnection)

Connects signal of sender to slot and returns a handle to the connection. slot is a member function of receiver, or any callable invoked in the context of receiver; it may accept fewer arguments than the signal provides. The connection is removed when either sender or receiver is destroyed.

type selects direct or queued delivery. Returns an invalid connection if sender is nullptr.

See also disconnect(), sender() and Signals and Slots.

template <typename SenderT, typename SignalClass, typename... SArgs, typename Func>[static] QMetaObject::Connection QObject::connect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), Func &&slot, Qt::ConnectionType type = Qt::AutoConnection)

This is an overloaded function.

Connects signal of sender to the callable slot, which has no receiver object. type selects direct or queued delivery.

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

Connects signal of sender to member of receiver and returns a handle to the connection, or an invalid connection if it cannot be made. Name the signal with the SIGNAL() macro, and the member with SLOT() or SIGNAL(); the arguments of the member must be those of the signal, or a prefix of them:

QObject::connect(&counter, SIGNAL(valueChanged(int)), &display, SLOT(show(int)));

A warning is printed and no connection is made if either object is nullptr, the signal or the member does not exist, or their arguments are not compatible. type selects direct or queued delivery.

See also disconnect() and Signals and Slots.

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

This is an overloaded function.

Connects the signal signal of sender to the method method of receiver. Get the two QMetaMethod objects from the meta-objects of the classes, or with QMetaMethod::fromSignal().

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

This is an overloaded function.

Connects signal of sender to method of this object. This is the same as connect(sender, signal, this, method, type).

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

Called when something connects to signal of this object, after the connection was made, in the thread that connected. Reimplement it to start costly work only once somebody listens. The base implementation does nothing.

signal is invalid for a signal of a class that ntmoc did not process.

See also disconnectNotify() and isSignalConnected().

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

Called for events of type QEvent::User and above that are sent to the object. The base implementation does nothing; reimplement it to handle custom events delivered as event.

See also event() and QEvent::registerEventType().

[slot] void QObject::deleteLater()

Schedules this object for deletion. The object is deleted when control returns to the event loop, so it is safe to call from a slot connected to one of its own signals.

See also QCoreApplication::postEvent().

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

This signal is emitted immediately before the object obj is destroyed, from the destructor of QObject. Connected slots run while the derived part of the object is already gone.

Note: Unlike in Qt, it is not emitted while signals are blocked.

See also deleteLater().

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

This is an overloaded function.

Removes the connection connection and returns true if it was connected; otherwise returns false.

See also connect().

template <typename SenderT, typename SignalClass, typename... SArgs>[static] bool QObject::disconnect(const SenderT *sender, void (SignalClass::*signal)(SArgs...), const QObject *receiver = nullptr, std::nullptr_t = nullptr)

Disconnects signal of sender from receiver, or from all receivers if receiver is nullptr. Returns true if any connection was removed; otherwise returns false. The last parameter is unused and exists for compatibility.

See also connect().

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

Removes the connections from signal of sender to member of receiver and returns true if any was removed. signal and member are named with SIGNAL() and SLOT(). A nullptr signal matches every signal, a nullptr receiver every receiver, and a nullptr member every member of the receiver.

See also connect().

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

This is an overloaded function.

Removes the connections from signal of sender to method of receiver. An invalid signal matches every signal, and an invalid method every method of the receiver.

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

This is an overloaded function.

Removes the connections from signal of this object to member of receiver, named with SIGNAL() and SLOT(). With no arguments, removes every connection from this object.

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

This is an overloaded function.

Removes the connections from this object to receiver, or only those to member, which is named with SLOT().

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

Called when a connection from signal of this object is removed by a disconnect call or after a Qt::SingleShotConnection was used, in the thread that removed it. It is not called for connections removed because the sender or the receiver is destroyed. The base implementation does nothing.

See also connectNotify().

void QObject::dumpObjectInfo() const

Writes the connections of this object to the debug output: those from its signals (SIGNALS OUT) and those to it (SIGNALS IN). Use it while debugging.

See also dumpObjectTree().

void QObject::dumpObjectTree() const

Writes the tree of this object and its descendants to the debug output, one object per line as ClassName::objectName, indented by depth. Use it while debugging.

See also dumpObjectInfo().

QList<QByteArray> QObject::dynamicPropertyNames() const

Returns the names of the dynamic properties of the object, in the order they were created.

See also setProperty().

template <typename Obj, typename... Args>[protected] void QObject::emitSignal(void (Obj::*signal)(Args...), const std::decay_t<Args> &...args)

Emits signal with args to every connected slot. This stands in for the body that ntmoc generates; call it from each signal function.

See also connect().

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

Receives event, an event sent to the object, and returns true if it was recognised and handled; otherwise returns false.

The base implementation dispatches QEvent::Timer events to timerEvent(), child events to childEvent(), runs queued slot invocations, and passes events of type QEvent::User and above to customEvent().

See also timerEvent(), childEvent() and customEvent().

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

Filters the events for watched, an object that this one is installed on as an event filter. Return true to stop event, so that watched does not get it, or false to let it go on. The default implementation returns false.

bool KeyLogger::eventFilter(QObject *watched, QEvent *event) {
    if (event->type() == QEvent::KeyPress)
        qDebug() << "key for" << watched;
    return false;
}

See also installEventFilter().

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

Returns the first child of this object that can be cast to T and, if name is not empty, has that object name; otherwise returns nullptr. T must be a pointer type. Direct children are tried first, then descendants if options includes Qt::FindChildrenRecursively (the default).

See also findChildren() and children().

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

Returns all children of this object that can be cast to T and, if name is not empty, have that object name. T must be a pointer type. Descendants are included if options contains Qt::FindChildrenRecursively (the default).

See also findChild() and children().

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

Returns true if this object is an instance of the class className or of a class that inherits from it; otherwise returns false. The class name is that of the meta-object, so it is qualified with its namespaces.

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

void QObject::installEventFilter(QObject *filterObj)

Installs filterObj as an event filter of this object: its eventFilter() sees the events of this object before this object does. A filter installed on the application sees the events of all objects. The filter installed last runs first; installing a filter again moves it to the front. A deleted filter is removed.

See also removeEventFilter() and eventFilter().

bool QObject::isQuickItemType() const

Returns true if the object is a Qt Quick item; Nt has no Qt Quick, so this always returns false.

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

Returns true if at least one connection from signal of this object exists; otherwise returns false.

static const QMetaMethod changed = QMetaMethod::fromSignal(&Sensor::valueChanged);
if (isSignalConnected(changed))
    emit valueChanged(read());

See also receivers() and connectNotify().

bool QObject::isWidgetType() const

Returns true if the object is a widget (it inherits QWidget); otherwise returns false.

See also isWindowType().

bool QObject::isWindowType() const

Returns true if the object is a window (it inherits QWindow); otherwise returns false.

See also isWidgetType().

void QObject::killTimer(int id)

Stops the timer with the identifier id, as returned by startTimer().

See also startTimer().

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

Returns the meta-object of the class of this object. The result is that of the dynamic type, so it describes the derived class even when it is called through a base class pointer. A class that ntmoc did not process is described by its nearest base class that it did.

See also QMetaObject and inherits().

void QObject::moveToThread(QThread *targetThread)

Changes the thread affinity of this object and its children to targetThread. The object's timers, socket notifiers and posted events move with it, and QEvent::ThreadChange is sent to every object that moves. If targetThread is nullptr, the object lives in no thread and receives no events until it is moved to one.

The function must be called from the thread the object lives in, or for an object that lives in no thread; otherwise it prints a warning and does nothing. An object with a parent cannot be moved.

Note: The object must not be used by its old thread while it moves, and a QSocketNotifier or timer that the object owns must not be stopped from the new thread before the move has completed.

See also thread() and QThread.

QString QObject::objectName() const

Returns the object's name, which is empty by default.

See also setObjectName().

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

This signal is emitted after the object name has changed, with the new name as objectName.

See also setObjectName().

QObject * QObject::parent() const

Returns the parent object, or nullptr if the object has none.

See also setParent() and children().

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

Returns the value of the property name, or an invalid QVariant if there is no such property. A property that Q_PROPERTY() declares is read through its READ function; otherwise the dynamic property of that name is returned.

See also setProperty(), dynamicPropertyNames() and QMetaProperty::read().

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

Returns the number of connections from signal of this object, named with the SIGNAL() macro, or 0 if the object has no such signal.

if (receivers(SIGNAL(valueChanged(int))) > 0)
    computeExpensiveValue();

See also isSignalConnected().

void QObject::removeEventFilter(QObject *obj)

Removes obj from the event filters of this object.

See also installEventFilter().

QObject * QObject::sender() const

Returns the object that emitted the signal that is currently invoking a slot, or nullptr when no slot is being invoked from a signal.

The value is meaningful only while a slot runs because of a signal, and is tracked per thread.

[protected] int QObject::senderSignalIndex() const

Returns the method index of the signal that invoked the slot that is running, as QMetaMethod::methodIndex() gives it, or -1 when no slot is being invoked from a signal or ntmoc did not see the signal.

See also sender().

void QObject::setObjectName(const QString &name)

Sets the object's name to name.

See also objectName() and findChild().

void QObject::setParent(QObject *parent)

Makes parent the parent of this object, removing it from its previous parent. A nullptr parent makes it a top-level object. Does nothing if parent is this object or one of its descendants.

The previous parent receives a ChildRemoved event and the new one a ChildAdded event; see childEvent().

See also parent() and children().

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

Sets the property name to value. Returns true if the property is declared with Q_PROPERTY() and the value was written. For a name that is not declared, a dynamic property is created or changed and a QDynamicPropertyChangeEvent is sent to the object, and the function returns false; setting an invalid value removes a dynamic property.

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

bool QObject::signalsBlocked() const

Returns true if signals emitted by this object are blocked; otherwise returns false. Signals are not blocked by default.

See also blockSignals().

int QObject::startTimer(int intervalMs)

Starts a timer that fires every intervalMs milliseconds and returns its identifier, or 0 if intervalMs is negative. The object receives a QTimerEvent in timerEvent() each time the timer fires, until killTimer() is called or the object is destroyed. An interval of 0 fires whenever the event loop is idle.

See also killTimer(), timerEvent() and QTimer.

int QObject::startTimer(std::chrono::milliseconds interval)

This is an overloaded function.

Starts a timer that fires every interval and returns its identifier, or 0 if interval is negative.

QThread * QObject::thread() const

Returns the thread the object lives in, which is the thread that created it unless moveToThread() was called. The thread's event loop delivers the object's events and runs its timers. Returns nullptr for an object that was moved to no thread, and for an object whose QThread has been destroyed.

See also moveToThread() and QThread::currentThread().

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

Called when a timer started with startTimer() fires. event identifies the timer through QTimerEvent::timerId(). The base implementation does nothing; reimplement it to handle timers.

See also startTimer() and event().