Question

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;
    }
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top