代码之家  ›  专栏  ›  技术社区  ›  jkyle

在qt4中跨类中继信号的正确方法?

  •  2
  • jkyle  · 技术社区  · 14 年前

    我有一个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是否是最佳实践,或者是否有其他更推荐的方法?

    1 回复  |  直到 14 年前
        1
  •  2
  •   David Walthall    14 年前

    有几种方法可以让你做的更干净一点。一种方法是更改向导以获取指向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();
    }
    

    我强烈建议使用第二种方法,因为它减少了子级需要知道父级细节的耦合。