StackedWidget的FindChild方法失败

时间:2016-08-21 19:41:48

标签: qt qstackedwidget

我在我的MainWindow类中使用了一个qstackedwidget,我在另一个类(PageLayouts)中定义了小部件,以便保持分离。但我正在MainWindow类中的对象之间建立连接(更改页面...),这会失败。基本上是:

//mainwindow.cpp
....

QSignalMapper * SM = new QSignalMapper(); 
Layouter = new PageLayouts();                 
//Instance of the class which contains the widgets 

QStackedWidget * Stack = new QStackedWidget(); 
Stack->addWidget(Layouter->getPage1());

connect(SM, SIGNAL(mapped(int)), Stack, SLOT(setCurrentIndex(int)));
SM->setMapping(Stack->widget(0)->findChild<QPushButton *>("Btn_ToPage2"), 1);

connect(Stack->widget(0)->findChild<QPushButton *>("Btn_ToPage2"), SIGNAL(clicked(bool)), SM, SLOT(map()));
.... 

//Debugging says to the first connect:
QObject::connect: Cannot connect (null)::destroyed() to QSignalMapper::_q_senderDestroyed()

//To the second:
QObject::connect: Cannot connect (null)::clicked(bool) to QSignalMapper::map()

我想我没有通过findchild方法正确获取PushButtons。 所以我的问题是:

  1. 如何在stackwidget中输入小部件的子节点?
  2. 由于我还在使用堆叠小部件进行实验,是否有更优雅的方式使用它们?
  3. 谢谢,塞巴斯蒂安

    编辑1:

    以下是在“pagelayouts.h”中生成Page1的代码:

    class PageLayouts
    {
    QWidget * Page1;
    QWidget * Page2;
    
    public:
    PageLayouts();
    
    //Get 
    QWidget * getPage1();
    ....
    

    在“pagelayouts.cpp”中生成page1的代码:

    PageLayouts::PageLayouts()
    {
    //Page1
    QHBoxLayout * HL_112 = new QHBoxLayout();   
    QVBoxLayout * VL_122 = new QVBoxLayout();                             
    
    QLabel * Lbl_NamePage1 = new QLabel("Page 1");
    QPushButton * Btn_ToPage2 = new QPushButton("Page 2");
    QPushButton * Btn_Close1 = new QPushButton("Close");
    
    //Assembling of Page1
    VL_122->addWidget(Btn_ToPage2);
    VL_122->addWidget(Btn_Close1);
    HL_112->addWidget(Lbl_NamePage1);
    HL_112->addLayout(VL_122);
    
    Page1 = new QWidget();
    Page1->setLayout(HL_112);
    
    //Page2
    ....
    }
    
    QWidget* PageLayouts::getPage1()
    {
    return Page1;
    }
    

    你可以看到它的实验代码,但我正在测试qstackedwidgets以进行进一步的设计决策,希望有人能解决这个问题。

1 个答案:

答案 0 :(得分:0)

您正在将“Btn_ToPage2”作为名称传递给QObject::findChild()。变量的名称为Btn_ToPage2,但您没有设置对象名称:

Btn_ToPage2->setObjectName("Btn_ToPage2");