Slot not called for QSplashScreen
Question
I'm trying to show a start-up image using QSplashScreen
and I want to show the image for about 2 seconds.
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QPixmap pixmap(":/images/usm.png");
QSplashScreen splash(pixmap);
splash.show();
splash.showMessage("Loading Processes");
QTimer::singleShot(2000, &splash, SLOT(close()));
MainWindow w;
w.show();
splash.finish(&w);
return a.exec();
}
But this is not working. QSplashScreen
appears for some milliseconds and then disappears. Tried to modify the time period but it seems like the QSplashScreen
object is not connected to slot. What's the problem and how to avoid it?
Solution
The problem with your code is that the timer is not blocking the execution so the splash screen has already closed with the splash.finish(&w)
call. What you need is a sleep. You could use a QWaitCondition
like this:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSplashScreen splash(QPixmap(":/images/usm.png"));
splash.show();
splash.showMessage("Loading Processes");
// Wait for 2 seconds
QMutex dummyMutex;
dummyMutex.lock();
QWaitCondition waitCondition;
waitCondition.wait(&dummyMutex, 2000);
MainWindow w;
w.show();
splash.finish(&w);
return a.exec();
}
The disadvantage of this approach is that you are blocking the execution. If you do not want to block it then you can simply remove the splash.finish(&w)
call:
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QPixmap pixmap(":/images/usm.png");
QSplashScreen splash(pixmap);
splash.show();
splash.showMessage("Loading Processes");
QTimer::singleShot(2000, &splash, SLOT(close()));
MainWindow w;
w.show();
return a.exec();
}
OTHER TIPS
This code should work:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSplashScreen splash(QPixmap(":/images/usm.png"));
splash.showMessage("Loading Processes");
splash->show();
QMainWindow w;
QTimer::singleShot(2000, splash, SLOT(close()));
QTimer::singleShot(2500, &w, SLOT(show()));
return a.exec();
}