Find the sender of the signal `destroy (QObject *)`

I'm currently wondering how to use the signal wisely QObject::destroyed(QObject*).

Observation

I noticed that the processed objects are QWidgetprocessed a little differently. Consider the following small self-sufficient and compiling example:

/* sscce.pro:
QT += core gui widgets
CONFIG += c++11
TARGET = sscce
TEMPLATE = app
SOURCES += main.cpp
*/

#include <QApplication>
#include <QPushButton>
#include <QTimer>
#include <QtDebug>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QPushButton *button = new QPushButton;
    QObject::connect(button, &QPushButton::destroyed,
        [=](QObject *o) { qDebug() << o; });

    delete button;

    QTimer *timer = new QTimer;
    QObject::connect(timer, &QTimer::destroyed,
        [=](QObject *o) { qDebug() << o; });

    delete timer;

    return app.exec();
}

This is his conclusion:

QWidget (0x1e9e1e0)
QObject (0x1e5c530)

Thus, presumably, the signal is emitted from QObjectd-tor, so only the base remains QObjectwhen the slot for is QTimercalled. However, QWidgetd-tor seems to intercept, as it still identifies itself as QWidgetfrom a slot.

And the problem

Suppose we have a timer pool that organizes a pair of timers in QList<QTimer *>:

struct Pool {
    QTimer *getTimer() {
        return timers.at(/* some clever logic here */);
    }        

    QList<QTimer *> timers;
};

, /. , . :

Pool::Pool() {
    /* for each timer created */
    connect(theTimer, SIGNAL(destroyed(QObject*),
        this, SLOT(timerDestroyed(QObject*));
}

void Pool::timerDeleted(QObject *object) {
    QTimer *theTimer = /* hrm. */
    timers.removeOne(theTimer);
}

? . , QTimer - QObject. qobject_cast<QTimer *>(object).

, :

  • QObject . , . , static_cast, , , QTimer, dynamic_cast qobject_cast.
  • removeOne iterator, QTimer QObject. QList::erase .
  • static_cast reinterpret_cast QObject QTimer.

?

, : -) [*]

[*]: , .

+4
2

, QObjectName .

+1

, - ; , , . Pool QTimer (, , delete ), , , QTimer& QTimer* getTimer. Qt, , , , , , std::unique_ptr<QTimer>.

+1

Source: https://habr.com/ru/post/1622000/


All Articles