3

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;
    }
}
László Papp
  • 51,870
  • 39
  • 111
  • 135
Suresh
  • 745
  • 4
  • 11
  • 25

1 Answers1

1

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • It is throwing an error as: request for member ‘setCurrentIndex’ in ‘((mywindow*)this)->mywindow::stack’, which is of non-class type ‘QStackedWidget* – Suresh Jan 08 '14 at 08:33
  • 1
    @user3153003: because you used '.' for accessing a member rather than '->' as it should be for pointers. – László Papp Jan 08 '14 at 08:41