在Qt中隐藏或显示QStackedWidget项

时间:2014-01-08 06:12:51

标签: c++ qt qwidget qtgui qt-events

我想在QStackedWidget中显示或隐藏项目。当我按下Enter按钮时,它应该显示一个堆叠元素,当我按下左按钮时它应该隐藏。 我使用QStackedWidgetQListWidget。我的代码:

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 个答案:

答案 0 :(得分:1)

您需要在按键事件处理程序中处理Key_Left和Key_Enter个案。看起来你只想根据按下那两个按钮来显示和隐藏stackwidget。这是一个简单的QWidget操作,问题与QStackedWidget没什么关系。

您需要更改按键事件代码,如下所示:

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

    }
 }