2013-03-06 32 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