简体   繁体   中英

Navigating through keyboard in QStackedWidget Item

I am trying to navigate QStackedWidget Item by using KeyPressEvent . But am not able to do it. What Signal function we should use for keyPressEvent ?

My Code:

mywindow::mywindow() : QMainWindow()

{   

    stack = new QStackedWidget();
    list1 = new QListWidget();
    list2 = new QListWidget();
    list3 = new QListWidget();

    list1->addItem("Item 1");
    list1->addItem("Item 2");

    list2->addItem("Item 3");
    list2->addItem("Item 4");

    list3->addItem("Item 5");
    list3->addItem("Item 6");

    stack->addWidget(list1);
    stack->addWidget(list2);
    stack->addWidget(list3);

    setCentralWidget(stack);
}

void mywindow::keyPressEvent(QKeyEvent *event)

{

    switch(event->key())
    {
        case Qt::Key_Left:
            connect(stack,SIGNAL(KeyPressEvent(QKeyEvent *event)),stack,SLOT(setCurrentIndex(int)));
            break;
     case Qt::Key_Right:
         connect(stack,SIGNAL(currentRowChanged(int)),stack,SLOT(setCurrentIndex(int)));
         break;
    }
}

You would need to get the current index and then increment that manually, and then set it. There is no "next" method for the class. So, you would be writing something like this:

void mywindow::keyPressEvent(QKeyEvent *event)

{

    switch(event->key())
    {
        case Qt::Key_Left:
            stack->setCurrentIndex(stack->currentIndex() - 1); // <--- Added
            break;
     case Qt::Key_Right:
            stack->setCurrentIndex(stack->currentIndex() + 1); // <--- Added
         break;
    }
}

Based on that QStackedWidget implementation, you may need to handle under and overflow yourself for the indices though, so be aware of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM