Hide or Show QStackedWidget Items in Qt

6.1k views Asked by At

I want to show or hide items in QStackedWidget. When I press Enter button it should show a stacked element and when I press say a left button it should hide. I use QStackedWidget and QListWidget. My code:

mymainwindow.h:

#ifndef MYMAINWINDOW_H
#define MYMAINWINDOW_H

class mymainwindow : public QMainWindow
{
    Q_OBJECT
public:
    mymainwindow();

protected:
  void keyPressEvent(QKeyEvent *event);

private:
  QStackedWidget *stack;
  QListWidget *list;
  QVBoxLayout *vertical;
  QWidget *widget;
};

#endif

mymainwindow.cpp:

#include "mymainwindow.h"

mymainwindow::mymainwindow() : QMainWindow()
{
    stack = new QStackedWidget();
    list = new QListWidget();

    stack->addWidget(new QLineEdit("Hello U have clicked the first menu"));
    stack->addWidget(new QLineEdit("Second ListWidget Item"));
    stack->addWidget(new QLineEdit("Last Widget Item"));

    widget = new QWidget();

    QLabel *label = new QLabel("Main Window");

    list->addItem("New Item 1");
    list->addItem("New Item 2");
    list->addItem("New Item 3");

    list->setFixedSize(200,100);

    QVBoxLayout *vertical = new QVBoxLayout();
    vertical->addWidget(label);
    vertical->addWidget(list);
    vertical->addWidget(stack);

    widget->setLayout(vertical);
    setCentralWidget(widget);
}

void mymainwindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Down:
        connect(list, SIGNAL(currentRowChanged(int)), stack, SLOT(setCurrentIndex(int)));
        break;
    case Qt::Key_Up:
        connect(list, SIGNAL(currentRowChanged(int)), stack, SLOT(setCurrentIndex(int)));
        break;
    case Qt::Key_Left:
        break;
    }
 }
1

There are 1 answers

0
László Papp On BEST ANSWER

You will need to handle the Key_Left and Key_Enter cases in your key press event handler. It seems that you would simply like to show and hide the stackwidget based on the press of those two buttons. This is a simple QWidget operation, and the problem is not much related to QStackedWidget.

You would need to change the key press event code as follows:

void mymainwindow::keyPressEvent(QKeyEvent *event)

 {

    switch (event->key()) {

     case Qt::Key_Down:
         connect(list,SIGNAL(currentRowChanged(int)),stack,SLOT(setCurrentIndex(int)));
         break;
     case Qt::Key_Up:
         connect(list,SIGNAL(currentRowChanged(int)),stack,SLOT(setCurrentIndex(int)));
         break;
      case Qt::Key_Left:
          stack->show(); // <---- Added

            break;
     case Qt::Key_Enter: // <---- Added
         stack->hide(); // <---- Added
         break;         // <---- Added

    }
 }