OrphanQDialog

// OrphanQDialog.h 

#ifndef ORPHANQDIALOG_H
#define ORPHANQDIALOG_H
 
#include <QDialog>
#include<vector>

class OrphanQDialog : public QDialog
{
    Q_OBJECT
public:
    explicit OrphanQDialog(QWidget *parent = 0);
    ~OrphanQDialog();

    static void MinimizeAll();
    static void RestoreAll();
    static void CloseAll();

protected:
    void changeEvent(QEvent *event);

private:
    int zOrderIndex;
    QPoint restorePosition;

    static std::vector<OrphanQDialog*> orphanDialogs;
    static unsigned int zOrderCounter;
};

#endif // ORPHANQDIALOG_H
 
 

// OrphanQDialog.cpp
 


#include "orphanqtdialog.h"
#include <QEvent>
#include <algorithm>

std::vector<OrphanQDialog*> OrphanQDialog::orphanDialogs;
unsigned int OrphanQDialog::zOrderCounter = 0;

OrphanQDialog::OrphanQDialog(QWidget *parent) :
    QDialog(parent), zOrderIndex(++zOrderCounter)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowFlags(windowFlags() | Qt::WindowMinimizeButtonHint);
    orphanDialogs.push_back(this);
}

OrphanQDialog::~OrphanQDialog()
{
    // NOTE TO SELF: DON'T TRY TO USE RANGE-FOR WHEN YOU CALL
    // METHODS THAT NEED AN ITERATOR
    for(auto it = orphanDialogs.begin(); it != orphanDialogs.end(); ++it)
    {
        if (*it == this)
        {
            orphanDialogs.erase(it);
            break;
        }
    }
}

void OrphanQDialog::MinimizeAll()
{
    for (auto window : orphanDialogs)
    {
        window->restorePosition = window->pos();
        window->hide();
    }
}

void OrphanQDialog::RestoreAll()
{
    zOrderCounter = 0;

    std::sort(orphanDialogs.begin(), orphanDialogs.end(), 
        [](OrphanQDialog* rhs, OrphanQDialog* lhs) -> bool
        { return rhs->zOrderIndex < lhs->zOrderIndex; });

    for (auto window : orphanDialogs)
    {
        window->move(window->restorePosition);
        window->show();
        window->zOrderIndex = ++zOrderCounter;
    }
}

void OrphanQDialog::CloseAll()
{
    for (auto window : orphanDialogs)
    {
        window->close();
    }
}

void OrphanQDialog::changeEvent(QEvent *event)
{
    QDialog::changeEvent(event);

    if (event->type() != QEvent::ActivationChange)
    {
        return;
    }

    if (isActiveWindow())
    {
        zOrderIndex = ++zOrderCounter;
    }
}

No comments:

Post a Comment