QObject

PyQt5.QtCore.QObject

Inherited by Q3DObject, Q3DScene, Q3DTheme, QAbstract3DAxis, QAbstract3DInputHandler, QAbstract3DSeries, QAbstractAnimation, QAbstractAnimation, QAbstractAspect, QAbstractAxis, QAbstractDataProxy, QAbstractEventDispatcher, QAbstractItemDelegate, QAbstractItemModel, QAbstractItemModelTester, QAbstractMessageHandler, QAbstractNetworkCache, QAbstractOAuth, QAbstractOAuthReplyHandler, QAbstractSeries, QAbstractState, QAbstractTextDocumentLayout, QAbstractTransition, QAbstractUriResolver, QAbstractVideoFilter, QAbstractVideoSurface, QAction, QActionGroup, QAnimationController, QAnimationGroup, QAspectEngine, QAudioInput, QAudioOutput, QAudioProbe, QAxObject, QBarSet, QBluetoothDeviceDiscoveryAgent, QBluetoothLocalDevice, QBluetoothServer, QBluetoothServiceDiscoveryAgent, QBluetoothTransferManager, QBluetoothTransferReply, QBoxSet, QButtonGroup, QCameraExposure, QCameraFocus, QCameraImageCapture, QCameraImageProcessing, QCandlestickModelMapper, QCandlestickSet, QClipboard, QCompleter, QCoreApplication, QCustom3DItem, QDataWidgetMapper, QDBusAbstractAdaptor, QDBusAbstractInterface, QDBusPendingCallWatcher, QDBusServiceWatcher, QDesignerFormEditorInterface, QDesignerFormWindowManagerInterface, QDnsLookup, QDrag, QEventLoop, QExtensionFactory, QExtensionManager, QFileSelector, QFileSystemWatcher, QGeoAreaMonitorSource, QGeoCodeReply, QGeoCodingManager, QGeoCodingManagerEngine, QGeoPositionInfoSource, QGeoRouteReply, QGeoRoutingManager, QGeoRoutingManagerEngine, QGeoSatelliteInfoSource, QGeoServiceProvider, QGesture, QGraphicsAnchor, QGraphicsApiFilter, QGraphicsEffect, QGraphicsObject, QGraphicsScene, QGraphicsTransform, QHBarModelMapper, QHBoxPlotModelMapper, QHelpEngineCore, QHelpFilterEngine, QHelpSearchEngine, QHPieModelMapper, QHttpMultiPart, QHXYModelMapper, QInAppProduct, QInAppStore, QInAppTransaction, QInputMethod, QIODevice, QItemSelectionModel, QJSEngine, QKeyEvent, QLayout, QLegendMarker, QLibrary, QLocalServer, QLowEnergyController, QLowEnergyService, QMacToolBar, QMacToolBarItem, QMaskGenerator, QMediaControl, QMediaObject, QMediaPlaylist, QMediaRecorder, QMediaService, QMimeData, QMorphTarget, QMouseEvent, QMovie, QNearFieldManager, QNearFieldShareManager, QNearFieldShareTarget, QNearFieldTarget, QNetworkAccessManager, QNetworkConfigurationManager, QNetworkCookieJar, QNetworkSession, QNode, QObjectCleanupHandler, QOffscreenSurface, QOpenGLContext, QOpenGLContextGroup, QOpenGLDebugLogger, QOpenGLShader, QOpenGLShaderProgram, QOpenGLTimeMonitor, QOpenGLTimerQuery, QOpenGLVertexArrayObject, QPdfWriter, QPickEvent, QPieSlice, QPlaceManager, QPlaceManagerEngine, QPlaceReply, QPluginLoader, QPyDesignerContainerExtension, QPyDesignerCustomWidgetCollectionPlugin, QPyDesignerCustomWidgetPlugin, QPyDesignerMemberSheetExtension, QPyDesignerPropertySheetExtension, QPyDesignerTaskMenuExtension, QQmlComponent, QQmlContext, QQmlEngineExtensionPlugin, QQmlExpression, QQmlExtensionPlugin, QQmlFileSelector, QQmlNdefRecord, QQmlPropertyMap, QQuick3DObject, QQuickImageResponse, QQuickItem, QQuickItemGrabResult, QQuickRenderControl, QQuickTextDocument, QQuickTextureFactory, QQuickWebEngineProfile, QQuickWebEngineScript, QRadioData, QRemoteObjectAbstractPersistedStore, QRemoteObjectNode, QRemoteObjectReplica, QRenderCapabilities, QRenderCaptureReply, QScreen, QScroller, QSensor, QSensorReading, QSessionManager, QSettings, QSGAbstractRenderer, QSGEngine, QSGTexture, QSGTextureProvider, QSharedMemory, QShortcut, QSignalMapper, QSignalSpy, QSocketNotifier, QSound, QSoundEffect, QSqlDriver, QStencilOperationArguments, QStencilTestArguments, QStyle, QStyleHints, QSvgRenderer, QSyntaxHighlighter, QSystemTrayIcon, QTcpServer, QTextDocument, QTextObject, QTextToSpeech, QTextureWrapMode, QThread, QThreadPool, QTimeLine, QTimer, QTranslator, QUndoGroup, QUndoStack, QValidator, QValue3DAxisFormatter, QVBarModelMapper, QVBoxPlotModelMapper, QVideoProbe, QVPieModelMapper, QVXYModelMapper, QWebChannel, QWebChannelAbstractTransport, QWebEngineCookieStore, QWebEngineDownloadItem, QWebEngineNotification, QWebEnginePage, QWebEngineProfile, QWebEngineUrlRequestInterceptor, QWebEngineUrlRequestJob, QWebEngineUrlSchemeHandler, QWebSocket, QWebSocketServer, QWheelEvent, QWidget, QWindow, QWinEventNotifier, QWinJumpList, QWinTaskbarButton, QWinTaskbarProgress, QWinThumbnailToolBar, QWinThumbnailToolButton.

Description

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

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 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 QTimer 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 QueuedConnection 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 run(), they cannot become children of the QThread object because the QThread does not live in the thread that calls 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 QObject, 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 connectSlotsByName() function.

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

Dynamic Properties

From Qt 4.2, 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.

From Qt 4.3, dynamic properties are supported by Qt 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(), Object Trees & Ownership.

Attributes

staticMetaObject: QMetaObject

This is a read-only class attribute.

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

Methods

__init__(parent: QObject = None)

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 0 constructs an object with no parent. If the object is a widget, it will become a top-level window.


blockSignals(bool) bool

TODO


childEvent(QChildEvent)

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

ChildAdded and 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).

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


children() List[QObject]

TODO


connectNotify(QMetaMethod)

TODO


customEvent(QEvent)

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 User item of the Type enum, and is typically a QEvent subclass. The event is passed in the event parameter.

See also

event(), QEvent.


deleteLater()

TODO


disconnect()

TODO


@staticmethod
disconnect(Connection) bool

TODO


disconnectNotify(QMetaMethod)

TODO


dumpObjectInfo()

TODO


dumpObjectTree()

TODO


dynamicPropertyNames() List[QByteArray]

TODO


event(QEvent) bool

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

The 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 = 0);
#     ~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);
#     }
# };

eventFilter(QObject, QEvent) bool

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 function, since the base class might have reimplemented for its own internal purposes.

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.


findChild(type, name: str = '', options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) QObject

TODO


findChild(tuple, name: str = '', options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) QObject

TODO


findChildren(type, name: str = '', options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


findChildren(tuple, name: str = '', options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


findChildren(type, QRegExp, options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


findChildren(tuple, QRegExp, options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


findChildren(type, QRegularExpression, options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


findChildren(tuple, QRegularExpression, options: Union[FindChildOptions, FindChildOption] = FindChildrenRecursively) List[QObject]

TODO


__getattr__(str) object

TODO


inherits(str) bool

TODO


installEventFilter(QObject)

TODO


isSignalConnected(QMetaMethod) bool

TODO


isWidgetType() bool

TODO


isWindowType() bool

TODO


killTimer(int)

TODO


metaObject() QMetaObject

TODO


moveToThread(QThread)

TODO


objectName() str

See also

setObjectName().


parent() QObject

See also

setParent().


property(str) Any

See also

setProperty().


pyqtConfigure(object)

TODO


receivers(PYQT_SIGNAL) int

TODO


removeEventFilter(QObject)

TODO


sender() QObject

TODO


senderSignalIndex() int

TODO


setObjectName(str)

See also

objectName().


setParent(QObject)

See also

parent().


setProperty(str, Any) bool

See also

property().


signalsBlocked() bool

TODO


startTimer(int, timerType: TimerType = CoarseTimer) int

TODO


thread() QThread

TODO


timerEvent(QTimerEvent)

TODO


tr(str, disambiguation: str = None, n: int = -1) str

TODO

Signals

destroyed(object: QObject = None)

TODO


objectNameChanged(str)

TODO