tags:

views:

24

answers:

1

I have a QMainWindow which spawns a few wizards. The QMainWindow has a QFrame class that lists a collection of objects. I want to launch this window from within my wizard's QWizardPages.

Basically, I need to connect a signal to a slot in the grand parent. The most obvious way to do this would be:

MyMainWindow *mainWindow = qobject_cast<MyMainWindow *>(parent->parent());

if(mainWindow) 
{
  connect(button, SIGNAL(clicked()), mainWindow, SLOT(launchWidgetOne()));
} else 
{
  qDebug() << "Super informative debug message";
}

Being new to qt4, I'm wondering if traversing the parent tree and qobject_cast are best practice or if there's a another means of doing this that is more recommended?

+1  A: 

There are a couple of ways that you can do this that are a little bit cleaner. One way is that you can change the Wizard to take a pointer to the MyMainWindow class. Then you can do the connect a little bit more cleanly.

class Page : public QWizardPage
{
public:
    Page(MyMainWindow *mainWindow, QWidget *parent) : QWizardPage(parent)
    {
        if(mainWindow) 
        {
          connect(button, SIGNAL(clicked()), mainWindow, SLOT(launchWidgetOne()));
        } else 
        {
          qDebug() << "Super informative debug message";
        }
    }
    // other members, etc
};

A much simpler design is to just propogate the signal up. After all, if the clicking of that button is important to the parent, let the parent handle it:

class Page : public QWizardPage
{
public:
    Page(QWidget *parent) : QWizardPage(parent)
    {
        connect(button, SIGNAL(clicked()), this, SIGNAL(launchWidgetOneRequested()));
    }
signals:
    void launchWidgetOneRequested();
};

void MyMainWindow::showWizard() // or wherever you launch the wizard
{
    Page *p = new Page;
    QWizard w;
    w.addPage(p);
    connect(p, SIGNAL(launchWidgetOneRequested()), this, SLOT(launchWidgetOne()));
    w.show();
}

I highly recommend the second approach since it reduces coupling where the child would need to know the details of the parent.

David Walthall
I was considering the second method, but wasn't sure if that level of signal passing was advised/good practice. Thank you for clearing that up.
jkyle