2

我想在 中显示或隐藏项目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;
    }
 }
4

1 回答 1

1

您将需要在按键事件处理程序中处理 Key_Left 和 Key_Enter 情况。您似乎只想根据这两个按钮的按下来显示和隐藏堆栈小部件。这是一个简单的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

    }
 }
于 2014-01-08T06:26:56.973 回答