In a QWizard, the next button cannot accept key press event, but accepts mouse press event?

1.4k views Asked by At

I have a class inherits QWizard, and add 2 independent QWizardPage(s). Before go to the next page, I want to do some job (i.e. check internet connection) on the first page. User may click 'next' button by mouse, or directly press enter/return by keyboard since the 'next' button is focused by default. So I install a eventfilter for the button:

button(QWizard::NextButton)->installEventFilter(this);

Then in the wizard class implement the event handling code:

bool MyWizard::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == button(QWizard::NextButton))
    {
        if (currentId() == startPageId)
        {
            if (event->type() == QEvent::KeyPress)
            {
                QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
                if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)
                {
                    // Do something. Cannot be reached.
                }
            }
            else if (event->type() == QEvent::MouseButtonPress)
            {
                // Do something. Can be reached.
            }
        }
    }    
    return QWizard::eventFilter(watched, event);
}

As I tried many times, clicking mouse can always make my event processing code run, but pressing key makes nothing to do. Another curious thing is, press mouse on button without releasing, then move away and release, the wizard stays on first page, now I can press key and all that is OK.

Could any one help to find the reason, is that a Qt bug? how can I make the key event work properly?

1

There are 1 answers

4
ScarCode On BEST ANSWER

Try another simple solution without installing event filter.Use QkeyPressEvent in your main App.

void YourAppClass::keyPressEvent(QKeyEvent *e)
{
     if(Nextbutton->hasFocus() && e->key()== Qt::Key_Return || e->key() == Qt::Key_Enter)
     {
     Do your job//I guarantee this will be reached upon pressing return with button focus
     }
}

You can add mouse-click functionality in nextbutton's clickevent().