1

我试图在我的主窗口打开之前从 QSplashScreen 获取按键。我的启动类继承自 QSplashScreen 并覆盖了 keyPressEvent 方法。

下面的代码适用于 Windows,但在 OSX 上,在主窗口打开之前不会拦截按键。

有解决方法吗?

这是使用 Qt 5.2.1,但我认为这个问题也在早期(4.X)版本中。

飞溅.cpp:

...

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

主.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();
}
4

1 回答 1

0

我通过在创建启动画面之前创建一个不可见的窗口来解决这个问题。

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();

    ...
于 2014-05-19T20:54:13.133 回答