2013-03-06 28 views
1

我正在测试如何使用StackedLayout在按下特定按钮时更改屏幕上的布局。使用Qt中的StackedLayout类

test.h

#ifndef TEST_H 
#define TEST_H 

#include <QLabel> 
#include <QApplication> 
#include <QLabel> 
#include <QPushButton> 
#include <QHBoxLayout> 
#include <QStackedLayout> 
#include <QVBoxLayout> 
#include <QComboBox> 

class Test: public QWidget{ 
    Q_OBJECT 

private: 
    QPushButton *button1, *button2; 
    QWidget *parentWidget1, *parentWidget2; 
    QLabel *label1, *label2; 
    QHBoxLayout *layout1, *layout2; 
    QStackedLayout *stackedLayout; 
    QHBoxLayout *mainLayout; 

private slots: 
    void layout1_h(); 
    void layout2_h(); 

public: 
    Test(QWidget* parent=0); 

}; 


#endif 

TEST.CPP

#include "test.h" 
using namespace std; 

void Test::layout1_h() 
{ 
    stackedLayout->setCurrentIndex(0); 
    //window->show(); 
} 

void Test::layout2_h() 
{ 
    stackedLayout->setCurrentIndex(1); 
    //window->show(); 
} 



Test::Test(QWidget *parent):QWidget(parent) 
{ 
    //widget = new QWidget; 
    stackedLayout = new QStackedLayout; 
    parentWidget1 = new QWidget; 
    parentWidget2 = new QWidget; 
    button1 = new QPushButton("change1"); 
    button2 = new QPushButton("change2"); 
    label1 = new QLabel("hello1"); 
    label2 = new QLabel("hello2"); 
    layout1 = new QHBoxLayout; 
    layout2 = new QHBoxLayout; 

    layout1->addWidget(label1); 
    layout1->addWidget(button1); 
    layout1->addWidget(button2); 

    layout2->addWidget(label2); 
    layout2->addWidget(button1); 
    layout2->addWidget(button2); 

    parentWidget1->setLayout(layout1); 
    parentWidget2->setLayout(layout2); 
    stackedLayout->addWidget(parentWidget1); 
    stackedLayout->addWidget(parentWidget2); 
    stackedLayout->setCurrentIndex(0); 
    mainLayout = new QHBoxLayout; 
    mainLayout->addLayout(stackedLayout); 

    connect(button1, SIGNAL(clicked()), this, SLOT(layout1_h())); 
    connect(button2, SIGNAL(clicked()), this, SLOT(layout2_h())); 

    setLayout(mainLayout); 
    //window.show(); 

} 

所以我的应用程序启动并运行,但由于某种原因,不显示的按钮。怎么了??

+0

您是否为堆叠布局设置了当前选项卡('stackedLayout-> setCurrentIndex(0)')?为什么不使用Qt Designer(与Qt Creator集成或独立)来组成用户界面? – 2013-03-06 11:04:29

+0

@Violet Girraffe:我现在这样做了。但结果是一样的(查看编辑后的代码)。我将使用Qt创建器,但现在我想了解一些Qt编程的感受。 – sudeepdino008 2013-03-06 11:12:42

+0

'mainLayout'似乎是不必要的,把它扔掉,只是做:'setCentralWidget(stackedLayout);' 但是,接下来,让设计师做肮脏的工作。不要手动创建布局。 – 2013-03-06 11:17:56

回答

2

button1和button2不能同时在两个布局中。 layout2成为两个按钮的管理器,parentWidget2成为它们的所有者。

+0

啊哈!很好的观察。谢谢! – sudeepdino008 2013-03-06 11:18:16