Implementing a widget stack in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Introduction[edit | edit source]

The QStackedWidget class provides a widget stack where only one widget is visible at a time. QStackedWidget provides no intrinsic means for the user to switch page.

Source Code[edit | edit source]

Header File[edit | edit source]

  1. ifndef STACK_H
  2. define STACK_H
  1. include <QtGui/QWidget>
  2. include<QWidget>
  3. include<QStackedWidget>
  4. include<QComboBox>
  5. include<QVBoxLayout>
  6. include<QPushButton>

class stack : public QWidget {

   Q_OBJECT

public:

   stack(QWidget *parent = 0);
   ~stack();

private:

   QPushButton *but;
   QPushButton *but1;
   QPushButton *but2;
   QVBoxLayout *lay;
   QVBoxLayout *lay1;
   QVBoxLayout *lay2;

};

  1. endif // STACK_H

Source File[edit | edit source]

  1. include "stack.h"

stack::stack(QWidget *parent)

   : QWidget(parent)

{ setStyleSheet("* { background-color:rgb(190,88,88);color:rgb(255,255,255); padding: 7px }}");

    QWidget *firstPageWidget = new QWidget(this);//First Widget
    lay=new QVBoxLayout(this);
    but=new QPushButton("First Widget",this);
    lay->addWidget(but);
    firstPageWidget->setLayout(lay);
    QWidget *secondPageWidget = new QWidget(this);//Second Widget
    lay1=new QVBoxLayout(this);
     but1=new QPushButton("second Widget",this);
    lay1->addWidget(but1);
    secondPageWidget->setLayout(lay1);


    QWidget *thirdPageWidget = new QWidget(this);//Third Widget
    lay2=new QVBoxLayout(this);
    but2=new QPushButton("Third Widget",this);
    lay2->addWidget(but2);
    thirdPageWidget->setLayout(lay2);


    QComboBox *pageComboBox = new QComboBox(this);
    QStackedWidget *stackedWidget = new QStackedWidget(this);
    stackedWidget->addWidget(firstPageWidget);
    stackedWidget->addWidget(secondPageWidget);
    stackedWidget->addWidget(thirdPageWidget);


    pageComboBox->addItem(tr("Page 1"));
    pageComboBox->addItem(tr("Page 2"));
    pageComboBox->addItem(tr("Page 3"));
    connect(pageComboBox, SIGNAL(activated(int)),stackedWidget, SLOT(setCurrentIndex(int)));
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(stackedWidget);
    layout->addWidget(pageComboBox);
    setLayout(layout);

}

stack::~stack() {

   // No need to delete any object that got a parent that is properly deleted.

}

Screenshot[edit | edit source]

File:Stackwin.JPG

File:Stackwind.JPG

Related Article[edit | edit source]

Archived:How to use QStackedLayout

pt:Archived:Implementando uma pilha de Widget (QStackedWidget)