C++ 在Qt中隐藏或显示QStackedWidget项
我想在C++ 在Qt中隐藏或显示QStackedWidget项,c++,qt,qwidget,qtgui,qt-events,C++,Qt,Qwidget,Qtgui,Qt Events,我想在QStackedWidget中显示或隐藏项目。当我按Enter按钮时,它应该显示一个堆叠的元素,当我按say left按钮时,它应该隐藏。 我使用QStackedWidget和QListWidget。我的代码: mymainwindow.h: #ifndef MYMAINWINDOW_H #define MYMAINWINDOW_H class mymainwindow : public QMainWindow { Q_OBJECT public: mymainwindo
QStackedWidget
中显示或隐藏项目。当我按Enter按钮时,它应该显示一个堆叠的元素,当我按say left按钮时,它应该隐藏。
我使用QStackedWidget
和QListWidget
。我的代码:
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;
}
}
您需要在按键事件处理程序中处理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
}
}
void mymain窗口::按键事件(QKeyEvent*event)
{
开关(事件->键()){
案例Qt::按键向下:
连接(列表、信号(currentRowChanged(int))、堆栈、插槽(setCurrentIndex(int));
打破
案例Qt::键向上:
连接(列表、信号(currentRowChanged(int))、堆栈、插槽(setCurrentIndex(int));
打破
案例Qt::左键:
堆栈->显示()//