Qt QObject Class: Complete Technical Reference

The QObject class serves as the foundation for all Qt widgets and core components. This class provides the essential infrastructure for Qt's signal-slot mechanism, event processing, property system, and object hierarchy management.

Header and Build Configuration

#include <QObject>

// In .pro file:
QT += core

Core Features

Signal-Slot Mechanism

QObject enables inter-object communication through Qt's signal-slot architecture. The connect() method establishes connections between signals and slots, while disconnect() removes them. The Q_OBJECT macro is essential for any class implementing signals, slots, or properties.

Event Handling

Objects can receive and process various event types including mouse clicks and keyboard input. The event() function handles event distribution and can be overridden in subclasses for custom behavior. Event filters installed via installEventFilter() allow intercepting events sent to other objects.

Timer Support

QObject provides built-in timer functionality through startTimer() and killTimer(). Multiple timers can run simultaneously, with each timer identified by a unique integer returned when started.

Property System

Dynamic properties can be added and accessed using property() and setProperty(). The property system integrates with Qt's meta-object system for runtime introspection.

Object Tree Management

QObject implements a parent-child hierarchy. When creating a QObject with another object as parent, the child automatically registers in the parent's children list. The parent owns children and deletes them in its destructor.

Thread Safety

Many QObject methods are thread-safe, enabling use in multi-threaded applications. The moveToThread() method changes an object's thread affinity.

Internationalization

All QObject subclasses support Qt's translation system. The tr() function retrieves translated strings:

tr(const char *sourceText, const char *disambiguation = nullptr, int n = -1)

Object Name Property

The objectName property provides a string identifier for objects, enabling lookup via findChild() and findChildren().

Access Functions

QString objectName() const;
void setObjectName(const QString &name);

Change Signal

void objectNameChanged(const QString &objectName);

This private signal emits when the object name changes, typically triggered by the framework internally.

Public Member Functions

Constructor

QObject::QObject(QObject *parent = nullptr);

Creates an object with optional parent. When parent is nullptr, the object has no parent. If the object is a widget, it becomes a top-level window. Parent objects own their children, automatically destroying them when the parent is destroyed.

Destructor

[virtual] QObject::~QObject();

Destroys the object and all children. Signal connections are automatically disconnected, and pending events are removed from queues. Prefer deleteLater() over direct deletion for safer asynchronous cleanup.

Signal Blocking

bool QObject::blockSignals(bool block);

Controls whether signals emitted by the object reach connected slots. When block is true, signals are suppressed. The destroyed signal still fires even when blocking is enabled. Blocked signals are not queued or cached.

Children Retrieval

const QObjectList &QObject::children() const;

Returns all child objects in creation order. QObjectList is equivalent to QList<QObject *>. The order changes when QWidget children are raised or lowered.

Connection Management

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

Establishes signal-slot connections. Each successful connection can emit a signal, so duplicate connections result in duplicate emissions.

Disconnection Funcsions

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

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

Removes signal-slot connections. With no arguments, disconnects all signals from the calling object. Connections automatically disconnect when involved objects are destroyed.

Debug Information

void QObject::dumpObjectInfo() const;
void QObject::dumpObjectTree() const;

Outputs debugging information including signal connections, object hierarchy, names, types, and addresses.

Dynamic Properties

QList<QByteArray> QObject::dynamicPropertyNames() const;

Returns names of properties dynamically added via setProperty().

Event Processing

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

Main event handler that processes events. Override to customize event handling:

class CustomWidget : public QWidget
{
    Q_OBJECT

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

    bool event(QEvent *ev) override
    {
        if (ev->type() == QEvent::PolishRequest) {
            performInitialization();
            return true;
        } else if (ev->type() == QEvent::Show) {
            performDisplaySetup();
            QWidget::event(ev);
            return true;
        }
        return QWidget::event(ev);
    }
};

Event Filter Installation

void QObject::installEventFilter(QObject *filterObj);
void QObject::removeEventFilter(QObject *obj);

Installs or removes event filters. Filters receive all events sent to the watched object. Multiple filters execute in reverse installation order.

class KeyInterceptor : public QObject
{
    Q_OBJECT

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

bool KeyInterceptor::eventFilter(QObject *target, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        qDebug("Captured key press: %d", keyEvent->key());
        return true;
    }
    return QObject::eventFilter(target, event);
}

// Usage:
KeyInterceptor *interceptor = new KeyInterceptor(this);
QPushButton *button = new QPushButton(this);
button->installEventFilter(interceptor);

If deleting the watched object within eventFilter, return true to prevent Qt from sending events to deleted objects.

Event Filter Handler

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

When an object serves as event filter, this function processes events before they reach the target. Return true to stop propagation, false to continue.

Child Search Functions

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

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

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

Search for child objects by name or type. Options include recursive search or direct children only.

QPushButton *btn = parentWidget->findChild<QPushButton *>("submitButton");
QList<QWidget *> allWidgets = parentWidget.findChildren<QWidget *>();
QList<QPushButton *> directButtons = 
    parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildrenOnly);

Type Checking

bool QObject::inherits(const char *className) const;
bool QObject::isWidgetType() const;
bool QObject::isWindowType() const;

Check object inheritance. isWidgetType() is equivalent to inherits("QWidget") but faster.

Timer Management

int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer);
int QObject::startTimer(std::chrono::milliseconds time, Qt::TimerType timerType = Qt::CoarseTimer);
void QObject::killTimer(int id);

Start timers with millisecond intervals. Override timerEvent() to handle timer expirations:

class TimerHandler : public QObject
{
    Q_OBJECT

public:
    TimerHandler(QObject *parent = nullptr);

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

TimerHandler::TimerHandler(QObject *parent)
    : QObject(parent)
{
    startTimer(100);      // 100ms interval
    startTimer(1s);       // 1 second interval
    startTimer(1min);     // 1 minute interval
}

void TimerHandler::timerEvent(QTimerEvent *event)
{
    qDebug() << "Timer triggered:" << event->timerId();
}

Timer types: Qt::PreciseTimer for high precision, Qt::CoarseTimer for lower precision.

Meta-Object Access

[virtual] const QMetaObject *QObject::metaObject() const;
static const QMetaObject QObject::staticMetaObject;

Access meta-object containing class information, properties, signals, and slots:

QObject *obj = new QPushButton;
obj->metaObject()->className();              // Returns "QPushButton"
QPushButton::staticMetaObject.className();   // Returns "QPushButton"

Thread Management

void QObject::moveToThread(QThread *targetThread);
QThread *QObject::thread() const;

Change object thread affinity. Event processing continues in the target thread. All active timers reset during move.

// Move to main application thread:
myObject->moveToThread(QApplication::instance()->thread());

// If targetThread is nullptr, all event processing stops.

This function is not thread-safe and can only push objects from the current thread.

Parent Management

QObject *QObject::parent() const;
void QObject::setParent(QObject *parent);

Manage object hierarchy:

QObject container;
QObject item;
item.setParent(&container);

QObject *itemParent = item.parent();
if (itemParent) {
    qDebug() << "Item has parent";
}

Property Access

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

Access declared or dynamic properties. Returns invalid QVariant if property doesn't exist.

// Set dynamic property
widget->setProperty("customData", QVariant(42));

// Read property
QVariant value = widget->property("customData");
if (value.isValid()) {
    int data = value.toInt();
}

For declared properties, setProperty() returns true on success. For dynamic properties (not in Q_PROPERTY), returns false after adding the property.

Signal Blocking Query

bool QObject::signalsBlocked() const;

Check if signal emission is blocked. Use with blockSignals() to control emission.

Public Slots

Delayed Deletion

[slot] void QObject::deleteLater();

Schedules object deletion at safe time. If event loop is running, deletion occurs after current event processes. Safe to call multiple times. Thread-safe and callable from any thread.

Signals

Destruction Signal

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

Emitted immediately before object destruction. Cannot be blocked even with blockSignals().

Name Change Signal

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

Private signal emitted after name changes. Used as property change notification.

Static Public Members

Connect Function Overloads

// Qt4 style with SIGNAL/SLOT macros
[static] QMetaObject::Connection QObject::connect(
    const QObject *sender, 
    const char *signal, 
    const QObject *receiver, 
    const char *method, 
    Qt::ConnectionType type = Qt::AutoConnection
);

// Qt5+ with member function pointers
template <typename PointerToMemberFunction>
QMetaObject::Connection QObject::connect(
    const QObject *sender, 
    PointerToMemberFunction signal, 
    const QObject *receiver, 
    PointerToMemberFunction method, 
    Qt::ConnectionType type = Qt::AutoConnection
);

// Functor connection
template <typename Functor>
QMetaObject::Connection QObject::connect(
    const QObject *sender, 
    PointerToMemberFunction signal, 
    Functor functor
);

Connection types:

  • Qt::AutoConnection: Auto-detect based on thread
  • Qt::DirectConnection: Execute slot immediately in sender thread
  • Qt::QueuedConnection: Execute in receiver's event loop
  • Qt::BlockingQueuedConnection: Block sender until slot completes
  • Qt::UniqueConnection: Fail if connection already exists
// Function pointer connection (Qt5+)
QLineEdit *editor = new QLineEdit;
QLabel *display = new QLabel;
connect(editor, &QLineEdit::textChanged, display, &QLabel::setText);

// Lambda connection
QTcpSocket *socket = new QTcpSocket;
connect(socket, &QTcpSocket::connected, [socket]() {
    socket->write("GET / HTTP\r\n\r\n");
});

// Qt4 style
connect(scrollBar, SIGNAL(valueChanged(int)), label, SLOT(setNum(int)));

Disconnect Function Overloads

// Disconnect all signals from object
myObject->disconnect();

// Disconnect specific signal
myObject->disconnect(SIGNAL(mySignal()));

// Disconnect from specific receiver
myObject->disconnect(receiverObject);

// Template version with member pointers
disconnect(sender, &SenderClass::signal, receiver, &ReceiverClass::slot);

Sender cannot be nullptr. Using nullptr for signal disconnects from all signals; using nullptr for receiver disconnects from all receivers.

Translation Function

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

Retrieves translated text. Use for internationalization:

QMenu *fileMenu = menuBar()->addMenu(tr("&File"));

Protected Member Functions

Child Event Handler

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

Receives child addition and removal events: QEvent::ChildAdded, QEvent::ChildRemoved, QEvent::ChildPolished.

Connection Notifications

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

Called when connections establish or break. Can determine which signal was connected using QMetaMethod::fromSignal().

Custom Event Handler

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

Handle custom user-defined events. Custom event types must be at least QEvent::User.

Signal Connection Check

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

Check if signal has any connected receivers:

static const QMetaMethod updateSignal = 
    QMetaMethod::fromSignal(&MyObject::dataUpdated);
if (isSignalConnected(updateSignal)) {
    QByteArray payload = fetchData();  // Expensive operation
    emit dataUpdated(payload);
}

Receiver Count Query

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

Returns count of connected receivers for a signal.

Sender Query

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

Within an executed slot, returns the object that emitted the triggering signal. Returns nullptr if called outside signal context.

Signal Index Query

[protected] int QObject::senderSignalIndex() const;

Returns meta-method index of signal that triggered current slot execution. Returns -1 if not in signal context.

Timer Event Handler

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

Handle timer expirations. Access timer ID via event->timerId().

Related Non-Members

Object List Type

typedef QObjectList QList<QObject *>;

Dynamic Cast

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

Qt's type-safe cast for QObject-derived classes. Returns nullptr if cast fails:

QObject *ptr = new QTimer;
QTimer *timer = qobject_cast<QTimer *>(ptr);    // Valid
QPushButton *button = qobject_cast<QPushButton *>(ptr);  // nullptr

Type T must declare Q_OBJECT macro.

Important Macros

Q_OBJECT

Required for any class using signals, slots, or properties:

class MyClass : public QObject
{
    Q_OBJECT
    // ...
};

Q_PROPERTY

Declare properties with meta-object system integration:

Q_PROPERTY(int count READ getCount WRITE setCount NOTIFY countChanged)
Q_PROPERTY(QString title MEMBER m_title)
Q_PROPERTY(bool active READ isActive CONSTANT)

Key specifiers:

  • READ: Getter function (required without MEMBER)
  • WRITE: Setter function (optional)
  • MEMBER: Bind to member variable (enables property()/setProperty())
  • NOTIFY: Signal for value changes
  • CONSTANT: Immutable value per instance
  • FINAL: Cannot be overridden by subclasses

Q_CLASSINFO

Attach metadata to classes:

class Document : public QObject
{
    Q_OBJECT
    Q_CLASSINFO("Version", "1.0")
    Q_CLASSINFO("Author", "Development Team")
};

// Access via metaObject()->classInfo()

All functions in this class are reentrant. The following functions are thread-safe: connect(), disconnect(), deleteLater(), blockSignals(), signalsBlocked(), and startTimer() with its variants.

Tags: Qt QObject C++ gui Meta-Object System

Posted on Fri, 05 Jun 2026 16:09:00 +0000 by oaf357