Skip to content

PythonQt.private.QObject · declarations 001

Back to PythonQt.private.QObject

blockSignals

blockSignals(b: bool) -> bool

X.blockSignals(b) -> bool

Supplemental documentation: Qt 5 reference:

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.

Upstream PySide2 reference signatures (binding differences may apply):

blockSignals(self, b: bool) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#blockSignals

childEvent

childEvent(event: Any) -> None

X.childEvent(event)

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

childEvent(self, event: PySide2.QtCore.QChildEvent) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#childEvent

children

children() -> tuple

X.children() -> tuple

Supplemental documentation: Qt 5 reference:

const QObjectList \&QObject::children() const

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

typedef QList<QObject*> QObjectList;

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

Upstream PySide2 reference signatures (binding differences may apply):

children(self) -> typing.List[PySide2.QtCore.QObject]

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#children

connect

connect(signal: Any, receiver: Any, slot: Any, type: Any) -> bool

X.connect(signal, receiver, slot, type) -> bool

Supplemental documentation: Qt 5 reference:

[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] 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.

This function was introduced in Qt 4.8.

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

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

[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 function can be connected to a given signal if the signal has at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments. 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.

Overloaded functions can be resolved with help of qOverload.

Note: This function is thread-safe.

[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 function can be connected to a given signal if the signal has at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments. 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.

This function was introduced in Qt 5.2.

Upstream PySide2 reference signatures (binding differences may apply):

connect(arg__1: PySide2.QtCore.QObject, arg__2: str, arg__3: typing.Callable, type: PySide2.QtCore.Qt.ConnectionType=...) -> bool
connect(self, arg__1: str, arg__2: typing.Callable, type: PySide2.QtCore.Qt.ConnectionType=...) -> bool
connect(self, arg__1: str, arg__2: PySide2.QtCore.QObject, arg__3: str, type: PySide2.QtCore.Qt.ConnectionType=...) -> bool
connect(self, sender: PySide2.QtCore.QObject, signal: str, member: str, type: PySide2.QtCore.Qt.ConnectionType=...) -> PySide2.QtCore.QMetaObject.Connection
connect(sender: PySide2.QtCore.QObject, signal: PySide2.QtCore.QMetaMethod, receiver: PySide2.QtCore.QObject, method: PySide2.QtCore.QMetaMethod, type: PySide2.QtCore.Qt.ConnectionType=...) -> PySide2.QtCore.QMetaObject.Connection
connect(sender: PySide2.QtCore.QObject, signal: str, receiver: PySide2.QtCore.QObject, member: str, type: PySide2.QtCore.Qt.ConnectionType=...) -> PySide2.QtCore.QMetaObject.Connection

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#connect

customEvent

customEvent(event: Any) -> None

X.customEvent(event)

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

customEvent(self, event: PySide2.QtCore.QEvent) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#customEvent

deleteLater

deleteLater() -> None

X.deleteLater()

Supplemental documentation: Qt 5 reference:

[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. Since Qt 4.8, 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.

Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.

Note: This function is thread-safe.

See also destroyed() and QPointer.

Upstream PySide2 reference signatures (binding differences may apply):

deleteLater(self) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#deleteLater

destroyed

destroyed(*args: Any, **kwargs: Any) -> Any

Native PythonQt.private.QObject.destroyed; argument details are not documented.

Supplemental documentation: Qt 5 reference:

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

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#destroyed

disconnect

disconnect(signal: Any, receiver: Any, slot: Any) -> bool

X.disconnect(signal, receiver, slot) -> bool

Supplemental documentation: Qt 5 reference:

[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);

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: This function is thread-safe.

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.

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.

This function was introduced in Qt 4.8.

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

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.

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

Note: This function is thread-safe.

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.

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

[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] 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, 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: 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: This function is thread-safe.

See also connect().

Upstream PySide2 reference signatures (binding differences may apply):

disconnect(arg__1: PySide2.QtCore.QMetaObject.Connection) -> bool
disconnect(arg__1: PySide2.QtCore.QObject, arg__2: str, arg__3: typing.Callable) -> bool
disconnect(self, arg__1: str, arg__2: typing.Callable) -> bool
disconnect(self, receiver: PySide2.QtCore.QObject, member: typing.Optional[str]=...) -> bool
disconnect(self, signal: str, receiver: PySide2.QtCore.QObject, member: str) -> bool
disconnect(sender: PySide2.QtCore.QObject, signal: PySide2.QtCore.QMetaMethod, receiver: PySide2.QtCore.QObject, member: PySide2.QtCore.QMetaMethod) -> bool
disconnect(sender: PySide2.QtCore.QObject, signal: str, receiver: PySide2.QtCore.QObject, member: str) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#disconnect

dumpObjectInfo

dumpObjectInfo() -> None

X.dumpObjectInfo()

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

dumpObjectInfo(self) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#dumpObjectInfo

dumpObjectTree

dumpObjectTree() -> None

X.dumpObjectTree()

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

dumpObjectTree(self) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#dumpObjectTree

dynamicPropertyNames

dynamicPropertyNames() -> Any

X.dynamicPropertyNames()

Supplemental documentation: Qt 5 reference:

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

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

This function was introduced in Qt 4.2.

Upstream PySide2 reference signatures (binding differences may apply):

dynamicPropertyNames(self) -> typing.List[PySide2.QtCore.QByteArray]

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#dynamicPropertyNames

event

event(event: Any) -> bool

X.event(event) -> bool

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

event(self, event: PySide2.QtCore.QEvent) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#event

eventFilter

eventFilter(watched: Any, event: Any) -> bool

X.eventFilter(watched, event) -> bool

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

eventFilter(self, watched: PySide2.QtCore.QObject, event: PySide2.QtCore.QEvent) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#eventFilter

findChild

findChild(type: Any, name: Any) -> Any

X.findChild(type, name) -> PythonQt.private.QObject

Supplemental documentation: Qt 5 reference:

template \<typename T> T QObject::findChild(const QString \&name \= QString(), Qt::FindChildOptions options \= ...) 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. Omitting the name argument causes all object names to be matched. 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 direct ancestors, it is undefined which one will be returned. In that case, findChildren() should be used.

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 *>(QString(), Qt::FindDirectChildrenOnly);

See also findChildren().

Upstream PySide2 reference signatures (binding differences may apply):

findChild(self, arg__1: type, arg__2: str=...) -> object

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#findChild

findChildren

findChildren(type: Any, name: Any) -> tuple

X.findChildren(type, name) -> tuple

Supplemental documentation: Qt 5 reference:

template \<typename T> QList\<T> QObject::findChildren(const QString \&name \= QString(), 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. Omitting the name argument causes all object names to be matched. 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 *>(QString(), Qt::FindDirectChildrenOnly);

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.

This function was introduced in Qt 5.0.

Upstream PySide2 reference signatures (binding differences may apply):

findChildren(self, arg__1: type, arg__2: PySide2.QtCore.QRegExp) -> typing.Iterable
findChildren(self, arg__1: type, arg__2: PySide2.QtCore.QRegularExpression) -> typing.Iterable
findChildren(self, arg__1: type, arg__2: str=...) -> typing.Iterable

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#findChildren

inherits

inherits(*args: Any, **kwargs: Any) -> bool

Returns if the class inherits or is of given type name

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

inherits(self, classname: str) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#inherits

installEventFilter

installEventFilter(filterObj: Any) -> None

X.installEventFilter(filterObj)

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

installEventFilter(self, filterObj: PySide2.QtCore.QObject) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#installEventFilter

isSignalConnected

isSignalConnected(signal: Any) -> bool

X.isSignalConnected(signal) -> bool

Supplemental documentation: Qt 5 reference:

[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 emitting a signal that nobody listens to.

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.

This function was introduced in Qt 5.0.

Upstream PySide2 reference signatures (binding differences may apply):

isSignalConnected(self, signal: PySide2.QtCore.QMetaMethod) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#isSignalConnected

isWidgetType

isWidgetType() -> bool

X.isWidgetType() -> bool

Supplemental documentation: Qt 5 reference:

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.

Upstream PySide2 reference signatures (binding differences may apply):

isWidgetType(self) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#isWidgetType

isWindowType

isWindowType() -> bool

X.isWindowType() -> bool

Supplemental documentation: Qt 5 reference:

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.

Upstream PySide2 reference signatures (binding differences may apply):

isWindowType(self) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#isWindowType

killTimer

killTimer(id: int) -> None

X.killTimer(id)

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

killTimer(self, id: int) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#killTimer

metaObject

metaObject() -> Any

X.metaObject() -> PythonQt.QtCore.QMetaObject

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

metaObject(self) -> PySide2.QtCore.QMetaObject

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#metaObject

moveToThread

moveToThread(thread: Any) -> None

X.moveToThread(thread)

Supplemental documentation: Qt 5 reference:

void QObject::moveToThread(QThread *targetThread)

Changes the thread affinity for this object and its children. 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().

Upstream PySide2 reference signatures (binding differences may apply):

moveToThread(self, thread: PySide2.QtCore.QThread) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#moveToThread

objectName instance-attribute

objectName: str

Qt 5 reference:

objectName : QString

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.

Access functions:

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

Notifier signal:

void objectNameChanged(const QString \&objectName) [see note below]

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

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

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#objectName

objectNameChanged

objectNameChanged(*args: Any, **kwargs: Any) -> Any

Native PythonQt.private.QObject.objectNameChanged; argument details are not documented.

Supplemental documentation: Qt 5 reference:

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

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#objectNameChanged

parent

parent() -> Any

X.parent() -> PythonQt.private.QObject

Supplemental documentation: Qt 5 reference:

QObject *QObject::parent() const

Returns a pointer to the parent object.

See also setParent() and children().

Upstream PySide2 reference signatures (binding differences may apply):

parent(self) -> PySide2.QtCore.QObject

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#parent

property

property(name: str) -> Any

X.property(name) -> object

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

property(self, name: str) -> typing.Any

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#property

removeEventFilter

removeEventFilter(obj: Any) -> None

X.removeEventFilter(obj)

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

removeEventFilter(self, obj: PySide2.QtCore.QObject) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#removeEventFilter

sender

sender() -> Any

X.sender() -> PythonQt.private.QObject

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

sender(self) -> PySide2.QtCore.QObject

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#sender

senderSignalIndex

senderSignalIndex() -> int

X.senderSignalIndex() -> int

Supplemental documentation: Qt 5 reference:

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

This function was introduced in Qt 4.8.

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

Upstream PySide2 reference signatures (binding differences may apply):

senderSignalIndex(self) -> int

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#senderSignalIndex

setObjectName

setObjectName(name: str) -> None

X.setObjectName(name)

Upstream PySide2 reference signatures (binding differences may apply):

setObjectName(self, name: str) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#setObjectName

setParent

setParent(parent: Any) -> None

X.setParent(parent)

Supplemental documentation: Qt 5 reference:

void QObject::setParent(QObject *parent)

Makes the object a child of parent.

See also parent() and children().

Upstream PySide2 reference signatures (binding differences may apply):

setParent(self, parent: PySide2.QtCore.QObject) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#setParent

setProperty

setProperty(name: str, value: Any) -> bool

X.setProperty(name, value) -> bool

Supplemental documentation: Qt 5 reference:

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

Upstream PySide2 reference signatures (binding differences may apply):

setProperty(self, name: str, value: typing.Any) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#setProperty

signalsBlocked

signalsBlocked() -> bool

X.signalsBlocked() -> bool

Supplemental documentation: Qt 5 reference:

bool QObject::signalsBlocked() const

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

See also blockSignals() and QSignalBlocker.

Upstream PySide2 reference signatures (binding differences may apply):

signalsBlocked(self) -> bool

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#signalsBlocked

startTimer

startTimer(interval: int, timerType: Any) -> int

X.startTimer(interval, timerType) -> int

Supplemental documentation: Qt 5 reference:

int QObject::startTimer(int time, 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 time interval until killTimer() is called. If time 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::timerId() 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)
{
    startTimer(50);     // 50-millisecond timer
    startTimer(1000);   // 1-second timer
    startTimer(60000);  // 1-minute timer

    using namespace std::chrono;
    startTimer(milliseconds(50));
    startTimer(seconds(1));
    startTimer(minutes(1));

    // since C++14 we can use std::chrono::duration literals, e.g.:
    startTimer(100ms);
    startTimer(5s);
    startTimer(2min);
    startTimer(1h);
}

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

Note that QTimer's accuracy 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 class provides 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 QTimer and less clumsy than using timer IDs directly.

This function was introduced in Qt 5.9.

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

Upstream PySide2 reference signatures (binding differences may apply):

startTimer(self, interval: int, timerType: PySide2.QtCore.Qt.TimerType=...) -> int

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#startTimer

thread

thread() -> Any

X.thread()

Supplemental documentation: Qt 5 reference:

QThread *QObject::thread() const

Returns the thread in which the object lives.

See also moveToThread().

Upstream PySide2 reference signatures (binding differences may apply):

thread(self) -> PySide2.QtCore.QThread

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#thread

timerEvent

timerEvent(event: Any) -> None

X.timerEvent(event)

Supplemental documentation: Qt 5 reference:

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

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

QTimer provides a higher-level interface 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().

Upstream PySide2 reference signatures (binding differences may apply):

timerEvent(self, event: PySide2.QtCore.QTimerEvent) -> None

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#timerEvent

tr

tr(text: Any, ambig: Any, n: Any) -> str

X.tr(text, ambig, n) -> str

Supplemental documentation: Qt 5 reference:

[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 MainWindow::createActions()
{
    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). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.

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

Upstream PySide2 reference signatures (binding differences may apply):

tr(self, arg__1: str, arg__2: str=..., arg__3: int=...) -> str

Source: https://doc.qt.io/archives/qt-5.15/qobject.html#tr