1

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?

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
develoops
  • 545
  • 2
  • 10
  • 21

2 Answers2

4

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();
}
pnezis
  • 12,023
  • 2
  • 38
  • 38
  • I think it would be better to make your MainWindow emit a signal when it's done initializing, and connect that to the splash screen. – Vishesh Handa Mar 09 '12 at 20:51
1

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();
}
talnicolas
  • 13,885
  • 7
  • 36
  • 56