1

I am trying to get keypresses from QSplashScreen before my main window opens. My splash class inherits from QSplashScreen and overrides the keyPressEvent method.

The code below works on Windows but on OSX the keypresses are not intercepted until the main window opens.

Is there a workaround for this?

This is using Qt 5.2.1, but I think this issue is also in earlier (4.X) versions too.

splash.cpp:

...

void Splash::keyPressEvent(QKeyEvent *evt)
{
     std::cout << evt->text().toStdString() << std::endl;
}

main.cpp:

...

void delay(float seconds)
{
     QTime dieTime= QTime::currentTime().addSecs(seconds);
     while( QTime::currentTime() < dieTime )
         QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

int main(int argc, char *argv[])
{
     QApplication a(argc, argv);

     Splash *splash = new Splash;
     splash->setPixmap(QPixmap(":/images/splash_loading.png"));
     splash->show();
     splash->grabKeyboard();

     // on OSX no keypresses captured here, on Windows keypresses captured
     delay(5.f);

     MainWindow w;
     w.show();

     // keypresses captured here on OSX and Windows
     delay(5.f);

     splash->releaseKeyboard();
     splash ->hide();

     return a.exec();
}
glennr
  • 2,069
  • 2
  • 26
  • 37
  • At a guess, it may be that the main event loop hasn't been created or initialised yet, so calling processEvents won't help. I suggest creating an event loop yourself, with QEventLoop and seeing if that makes a difference: http://qt-project.org/doc/qt-4.8/qeventloop.html#details – TheDarkKnight May 19 '14 at 09:04
  • Thanks, I tried creating a QEventLoop but that didn't work. – glennr May 19 '14 at 20:48

1 Answers1

0

I worked around this by creating an invisible window before creating the splashscreen.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Create a dummy window so that we get keypresses on OSX
    QLabel v(0, Qt::FramelessWindowHint);
    v.setMinimumSize(QSize(0, 0));
    v.move(0,0);
    v.show();

    Splash *splash = new Splash;
    splash->setPixmap(QPixmap(":/images/splash_loading.png"));
    splash->show();
    splash->grabKeyboard();

    // keypresses are now captured here
    delay(5.f);

    // hide the dummy window before showing the main one
    v.hide();
    MainWindow w;
    w.show();

    ...
glennr
  • 2,069
  • 2
  • 26
  • 37