2

我有一个 QMainWindow ,它产生了一些向导。QMainWindow 有一个列出对象集合的 QFrame 类。我想从我的向导的 QWizardPages 中启动这个窗口。

基本上,我需要将信号连接到祖父母的插槽。最明显的方法是:

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

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

作为 qt4 的新手,我想知道遍历父树和 qobject_cast 是否是最佳实践,或者是否有另一种更推荐的方法?

4

1 回答 1

2

有几种方法可以做到这一点,它们更简洁。一种方法是您可以更改向导以获取指向 MyMainWindow 类的指针。然后你可以更干净地进行连接。

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
};

一个更简单的设计是向上传播信号。毕竟,如果单击该按钮对父级很重要,则让父级处理它:

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();
}

我强烈推荐第二种方法,因为它减少了孩子需要知道父母细节的耦合。

于 2010-04-08T20:25:58.573 回答