2014-05-19 29 views
1

我想在打開主窗口之前從QSplashScreen中獲取按鍵按鍵。我的 splash類從QSplashScreen繼承並重寫keyPressEvent方法。在OSX上的QSplashScreen中獲取按鍵按鍵

下面的代碼在Windows上工作,但在OSX上,按下按鍵不會被攔截 ,直到主窗口打開。

是否有解決方法?

這是使用Qt 5.2.1,但我認爲這個問題也是早期的(4.X)版本。

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(); 
} 
+0

可能是主事件循環還沒有被創建或初始化,所以調用processEvents不會有幫助。我建議你自己創建一個事件循環,用QEventLoop,看看是否有所作爲:http://qt-project.org/doc/qt-4.8/qeventloop.html#details – TheDarkKnight

+0

謝謝,我試着創建一個QEventLoop,但那didn沒有工作。 – glennr

回答

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

    ...