Silicomancer
Silicomancer

Reputation: 9186

Centrally track opened and closed windows in Qt

I need some virtual function/signal/event in a QApplication that centrally informs about any opened and closed window in the application (providing a pointer to the window object; including QMainWindow, QDialog, QWidget based windows).

This should work without manually registering all window instances and without manually manipulating each instance (e.g. by installing event filters or connections on each window object). Also it should not be necessary to sub-class the tracked windows from some interface class or similar.

So, what is the best way in Qt to track all opened and closed windows in an application?

Upvotes: 1

Views: 371

Answers (1)

eyllanesc
eyllanesc

Reputation: 244162

You must overwrite the notify method of QApplication(or QGuiApplication):

#include <QtWidgets>

class Application: public QApplication
{
public:
    using QApplication::QApplication;
    bool notify(QObject *receiver, QEvent *e) override
    {
        if(receiver->isWindowType()){
            if(e->type() == QEvent::Show){
                qDebug()<< receiver << "show";
            }
            else if (e->type() == QEvent::Close) {
                qDebug()<< receiver << "close";
            }
        }
        return QApplication::notify(receiver, e);
    }
};

int main(int argc, char *argv[])
{
    Application a(argc, argv);
    QMainWindow m;
    QDialog d;
    QWidget w;
    m.show();
    d.show();
    w.show();
    return a.exec();
}

Update:

#include <QtWidgets>

class Application: public QApplication
{
public:
    using QApplication::QApplication;
    bool notify(QObject *receiver, QEvent *e) override
    {
        if(receiver->isWidgetType()){
            QWidget *w = qobject_cast<QWidget *>(receiver);
            if(w->isWindow()){
                if(e->type() == QEvent::Show){
                    qDebug()<< w << "show";
                }
                else if (e->type() == QEvent::Close) {
                     qDebug()<< w << "close";
                }
            }
        }
        return QApplication::notify(receiver, e);
    }
};

Upvotes: 1

Related Questions