May 4, 2012

entricular entricular
Lab Rat
11 posts

How to display a splash screen in Qt ?

Page  
1

Is this the correct way to display a splash screen in Qt ? This code was tested and confirmed( it works ) on Ubuntu Linux 10.04 LTS with Qt 4.7.4 SDK installed. I tested the code with Windows Vista and Qt 4.7.4 and it did not work.

Make sure you have the splashpage.png file in the directory. Use the GIMP http://www.gimp.org to create a simple splashpage image of 600 × 400. When you reply to this question please do not half or snippet your code please reply with the full source code and make sure you test you code before you post it. Snippets and half code is very frustrating to a newbie coder.

Instructions to run this code:

1. Create a directory, such as SplashPageApplication
2. Change into the directory
3. Create a file named main.cpp in your newly created directory, type/copy/paste the code below in the file save as main.cpp
4. Run qmake -project, qmake, make
5. Then run application

  1. #include <QtCore>
  2. #include <QApplication>
  3. #include <QPixmap>
  4. #include <QSplashScreen>
  5. #include <QWidget>
  6. #include <QMainWindow>
  7. #include <QTimer>
  8. #include <QThread>
  9.  
  10.  
  11.  
  12. class I : public QThread
  13. {
  14. public:
  15.         static void sleep(unsigned long secs) {
  16.                 QThread::sleep(secs);
  17.         }
  18. };
  19.  
  20. int main(int argc, char *argv[])
  21. {
  22.  
  23.     QApplication app(argc, argv);
  24.     QPixmap pixmap("splash.png"); //Insert your splash page image here
  25.     QSplashScreen splash(pixmap);
  26.     splash.show();
  27.  
  28.     splash.showMessage(QObject::tr("Initiating your program now..."),
  29.                     Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position
  30.  
  31.     qApp->processEvents();//This is used to accept a click on the screen so that user can cancel the screen
  32.  
  33.  
  34.  
  35.     QMainWindow mainWin;
  36.     mainWin.setWindowTitle("Qt Application"); //Set the title of your main Qt Application
  37.     mainWin.resize(600, 500);
  38.     I::sleep(5);               // Splash page is shown for 5 seconds
  39.  
  40.    mainWin.show(); //This will maximize to fullscreen the size of your application window after the splash page displays
  41.    splash.finish(&mainWin);
  42.    
  43.  splash.raise();  
  44. return app.exec();
  45. }

[Edit: Added @ tags; mlong]

19 replies

May 4, 2012

mlong mlong
Robot Herder
1551 posts

Please use @ tags around your code.

 Signature 

Senior Software Engineer
AccuWeather Enterprise Solutions
/* My views and opinions do not necessarily reflect those of my employer.  Void where prohibited. */

May 4, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts

Well, you create the Splash Screen and you show() it. But you are NOT running an event loop until the app.exec() at the very end. Your qApp->processEvents() probably is sufficient that the Splash Screen gets drawn once, but it certainly won’t be “responsive” to user actions. processEvents() processes all pending events, yes. But it won’t block and run a “loop” to wait for upcoming messages. Instead it will simply return as soon as possible!

I would use something like this and do all the required “initialization” work in a separate thread:

  1. int main(int argc, char *argv[])
  2. {
  3.     QApplication app(argc, argv);
  4.  
  5.     QPixmap pixmap("splash.png"); //Insert your splash page image here
  6.     if(pixmap.isNull())
  7.     {
  8.         QMessageBox::warning(0, "Error", "Failed to load Splash Screen image!");
  9.     }
  10.  
  11.     QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint);
  12.     splash.setEnabled(false); //Prevent user from closing the splash
  13.     splash.show();
  14.     app.processEvents(); //Make sure splash screen gets drawn ASAP
  15.  
  16.     QEventLoop loop;
  17.  
  18.     MyInitThread *thread = new MyInitThread();
  19.     QObject::connect(thread, SIGNAL(finished()), &loop, SLOT(quit()));
  20.     QObject::connect(thread, SIGNAL(terminated()), &loop, SLOT(quit()));
  21.     thread->start();
  22.  
  23.     loop.exec(); //Do event processing until the thread has finished!
  24.     splash.hide();
  25.  
  26.     QMainWindow mainWin;
  27.     mainWin.setWindowTitle("My Example Application");
  28.     mainWin.resize(640, 480);
  29.     mainWin.show();
  30.  
  31.     return app.exec();
  32. }

  1. class MyInitThread : public QThread
  2. {
  3. protected:
  4.     void run(void)
  5.     {
  6.         /* Do whatever needs to be done to init your application! */
  7.  
  8.         QThread::msleep(5000); //Sleep 5 sec to simulate work ;-)
  9.     }
  10. };

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 4, 2012

entricular entricular
Lab Rat
11 posts

@MuldeR
For the above code are these two or three separate files such as main.cpp, mainwindow.cpp, mainwindow.h ? Can you please tell me what you are naming your files. I rather have the full source code that you are submitting then snippets of code. I am having problems compiling your code using qmake -project, qmake, make.
Did you test this code ?
Does it work ?

May 4, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts

C++ does not force you to put each class in a separate .cpp files (with a corresponding .h file), but it usually is a good idea. If you want to, you can put everything into a single file of course. You can name your files as you like.

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 4, 2012

entricular entricular
Lab Rat
11 posts

Hey MuldeR

I tried modifying/hacking the initial code to include your suggestions and I usually get a bunch of error messages such as the following:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:32: error: ‘MyInitThread’ was not declared in this scope
main.cpp:32: error: ‘thread’ was not declared in this scope
main.cpp:32: error: expected type-specifier before ‘MyInitThread’
main.cpp:32: error: expected ‘;’ before ‘MyInitThread’
main.cpp:33: error: ‘connect’ was not declared in this scope
main.cpp:13: error: ‘static void I::sleep(long unsigned int)’ is protected
main.cpp:41: error: within this context
make: *** [main.o] Error 1

Do you think you can type/copy/paste this code with improvements or your suggestions that work ?

See the following code:

  1. #include <QtCore>
  2. #include <QApplication>
  3. #include <QPixmap>
  4. #include <QSplashScreen>
  5. #include <QWidget>
  6. #include <QMainWindow>
  7. #include <QTimer>
  8. #include <QThread>
  9.  
  10. class I : public QThread
  11. {
  12. protected:
  13.         static void sleep(unsigned long secs) {
  14.                 QThread::sleep(secs);
  15.         }
  16. };
  17.  
  18.  
  19. int main(int argc, char *argv[])
  20. {
  21.    QApplication app(argc, argv);
  22.  
  23.    QPixmap pixmap("splash.png"); //Insert your splash page image here
  24.    QSplashScreen splash(pixmap);
  25.    splash.show();
  26. splash.showMessage(QObject::tr("Initiating your program now..."),
  27.                     Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position
  28.  
  29.    app.processEvents(); //Make sure splash screen gets drawn ASAP
  30.   QEventLoop loop;
  31.  
  32.    MyInitThread *thread = new MyInitThread();
  33.    connect(thread, SIGNAL(finished()), &loop, SLOT(quit()));
  34.    thread->start();
  35.  
  36.    loop.exec(); //Do event processing until the thread has finished!
  37.  
  38. QMainWindow mainWin;
  39.     mainWin.setWindowTitle("Qt Application"); //Set the title of your main Qt Application
  40.     mainWin.resize(600, 500);
  41.     I::sleep(5);               // Splash page is shown for 5 seconds
  42.  mainWin.show(); //This will maximize to fullscreen the size of your application window after the splash page displays
  43.    splash.finish(&mainWin);
  44.    
  45.  splash.raise();  
  46. return app.exec();
  47. }

May 4, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts

“MyInitThread” was just an example/suggestion on how you could call your own thread class.

Apparently you tried to instantiate a MyInitThread object, but didn’t declare a class of that name ;)

You have a QThread-derived class “I” in your code, but why did you declare a sleep() method an call it directly?

That’s pretty much identical to calling Sleep(secs) in your main thread – it will block the main thread!

If you want to do something in a separate thread, then you’ll have to do this in the QThread’s run() method.

You can launch the new thread by calling QThread::start(). See my code above…

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 4, 2012

entricular entricular
Lab Rat
11 posts

Okay this is your code, that I will post below please fix your code so it compiles without errors. Is it possible for you to do that ?
All I did was add the #include directives and move the second half of the code to the beginning.
I would really like to see the full source code of your example/suggestion which works.
All you have to do is copy/paste the corrected code in the box it’s not too hard to do is it ?

  1. #include <QtCore>
  2. #include <QApplication>
  3. #include <QPixmap>
  4. #include <QSplashScreen>
  5. #include <QWidget>
  6. #include <QMainWindow>
  7. #include <QTimer>
  8. #include <QThread>
  9.  
  10. class MyInitThread : public QThread
  11. {
  12. protected:
  13.     void run(void)
  14.     {
  15.         /* Do whatever needs to be done to init your application! */
  16.     }
  17. };
  18.  
  19.  
  20. int main(int argc, char *argv[])
  21. {
  22.    QApplication app(argc, argv);
  23.  
  24.    QPixmap pixmap("splash.png"); //Insert your splash page image here
  25.    QSplashScreen splash(pixmap);
  26.    splash.show();
  27.    app.processEvents(); //Make sure splash screen gets drawn ASAP
  28.  
  29.    QEventLoop loop;
  30.  
  31.    MyInitThread *thread = new MyInitThread();
  32.    connect(thread, SIGNAL(finished()), &loop, SLOT(quit()));
  33.    thread->start();
  34.  
  35.    loop.exec(); //Do event processing until the thread has finished!
  36.  
  37.    QMainWindow mainWin;
  38.    splash.hide();
  39.    mainWin.show();
  40.  
  41.    return app.exec();
  42. }

May 4, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts

I think it should be straight forward to get the basic idea from the code I posted here:
http://qt-project.org/forums/viewreply/84757/

If you have a specific question, feel free to ask. But you can’t expect that somebody else will write the complete code for you. Instead you better learn how to do it yourself. But as it seems you have more problems with C++ in general than with Qt in particular, I would suggest to start with a basic C++ book/tutorial though…

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 7, 2012

KA51O KA51O
Ant Farmer
478 posts

This code [qt-project.org] I posted a while ago worked for me. Maybe its helpful for you.

May 7, 2012

entricular entricular
Lab Rat
11 posts

Hey KA510, I looked at the code you posted and although it is interesting it is not exactly what I am looking for. I noticed that this code you posted works only on Ubuntu Linux and I was looking for code that worked on both Linux and Windows. So far the closest I have come to what I am looking for is the following code below.

main.cpp

  1. #include <QtGui/QApplication>
  2. #include "splashscreen.h"
  3. #include "mainwindow.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     QApplication a(argc, argv);
  8.     MainWindow w;
  9.  
  10.     // lock orientation to portrait when showing the splash screen
  11.     w.lockPortraitOrientation();
  12.  
  13.     // SplashScreen is derived from QSplashScreen that blocks mouse
  14.     // press events, prevents user from clicking on splashscreen to
  15.     // hide it.
  16.     QPixmap pixmap(":/images/splash.png");
  17.     SplashScreen splash(true, pixmap, Qt::WindowStaysOnTopHint);
  18.    
  19.     // connect loader's progress notifications to splashscreen
  20.     QObject::connect(w.loader(), SIGNAL(progress(QString,int,QColor)),
  21.                         &splash, SLOT(showMessage(QString,int,QColor)));
  22.    
  23.    
  24.     // on loader done signal, close splashscreen and show mainwindow
  25.     QObject::connect(w.loader(), SIGNAL(done()), &splash, SLOT(close()));
  26.      
  27. #if defined(Q_WS_S60)
  28.     QObject::connect(w.loader(), SIGNAL(done()), &w, SLOT(startUpMaximized()));
  29. #else
  30.      QObject::connect(w.loader(), SIGNAL(done()), &w, SLOT(startUpMaximized()));
  31. #endif
  32.  
  33.    
  34.     splash.show();
  35.     splash.raise();
  36.    
  37.     return a.exec();
  38. }

mainwindow.cpp

  1. #include "mainwindow.h"
  2. #include <QtGui/QApplication>
  3. #include <QMenuBar>
  4. #include <QWidgetList>
  5.  
  6. // needed for S60-specific orientation/softkey handling
  7. #ifdef Q_WS_S60
  8. #include <coemain.h>
  9. #include <aknappui.h>
  10. #endif
  11.  
  12.  
  13. DummyLoader::DummyLoader(QObject *parent)
  14.   : QObject(parent),
  15.     m_progress(0)
  16. {
  17.   m_states.insert(15, "Loading resources");
  18.   m_states.insert(30, "Validating");
  19.   m_states.insert(50, "Loading plugins");
  20.   m_states.insert(66, "Initializating");
  21.   m_states.insert(100, "Preparing to launch");
  22.    
  23.   connect(&m_timer, SIGNAL(timeout()), this, SLOT(doSomething()));
  24.   m_timer.start(500);
  25. }
  26.  
  27.  
  28. // simulates some activity and fires off notification signals
  29. void DummyLoader::doSomething()
  30. {
  31.     m_progress += (qrand() % 5) + 3;
  32.     m_progress = qMin(100, m_progress);
  33.    
  34.     if ( m_progress == 100 ) {
  35.         m_timer.stop();
  36.         emit done();
  37.         return;
  38.     }
  39.    
  40.     QMap<int, QString>::const_iterator i = m_states.lowerBound(m_progress);
  41.     if ( i != m_states.constEnd() ) {
  42.         QString progressMsg = QString("%1...").arg(i.value());
  43.         emit progress(progressMsg,  Qt::AlignLeft | Qt::AlignTop, Qt::red);
  44.     }
  45. }
  46.  
  47.  
  48. MainWindow::MainWindow(QWidget *parent) :
  49.     QMainWindow(parent),
  50.     m_orientation(-1)
  51. {
  52.     menuBar()->addAction(tr("Exit"), this, SLOT(close()));
  53.     removeContextMenus();
  54.    
  55.     // a dummy progresss notifier as if we were loading something...
  56.     m_loader = new DummyLoader(this);
  57.  
  58. }
  59.  
  60.  
  61. void MainWindow::removeContextMenus()
  62. {
  63.     // Remove context menu from the all widgets.
  64.     QWidgetList widgets = QApplication::allWidgets();
  65.     QWidget* w=0;
  66.     foreach(w,widgets) {
  67.         w->setContextMenuPolicy(Qt::NoContextMenu);
  68.     }
  69. }
  70.  
  71.  
  72. void MainWindow::startUpMaximized()
  73. {
  74.     // release orientation lock (if set)
  75.     releaseOrientation();
  76.  
  77.     setWindowFlags(windowFlags() | Qt::WindowSoftkeysVisibleHint);
  78.     showMaximized();
  79. }
  80.  
  81.  
  82. // Lock S60 app orientation to portrait - used when showing the splash screen
  83. void MainWindow::lockPortraitOrientation()
  84. {
  85. #ifdef Q_WS_S60
  86.     CAknAppUi* s60AppUi = dynamic_cast<CAknAppUi*> (CCoeEnv::Static()->AppUi());
  87.     // save the old orientation
  88.     m_orientation = (int)s60AppUi->Orientation();
  89.     TRAP_IGNORE(
  90.         if (s60AppUi) {
  91.         // Lock portrait orientation when showing the splash screen
  92.         s60AppUi->SetOrientationL(CAknAppUi::EAppUiOrientationPortrait);
  93.     });
  94. #endif
  95. }
  96.  
  97.  
  98. // Releases the orientation lock (restores previous orientation)
  99. void MainWindow::releaseOrientation()
  100. {
  101.     // do nothing if orientation is not locked
  102.     if( m_orientation == -1 )
  103.         return;
  104.  
  105. #ifdef Q_WS_S60
  106.     CAknAppUi* s60AppUi = dynamic_cast<CAknAppUi*> (CCoeEnv::Static()->AppUi());
  107.  
  108.     TRAP_IGNORE(
  109.         if (s60AppUi) {
  110.         s60AppUi->SetOrientationL((CAknAppUiBase::TAppUiOrientation)m_orientation);
  111.     });
  112. #endif
  113. }

mainwindow.h
  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QTimer>
  6. #include <QMap>
  7.  
  8. class DummyLoader : public QObject
  9. {
  10.   Q_OBJECT
  11.  
  12. public:
  13.   explicit DummyLoader(QObject *parent = 0);
  14.  
  15. signals:
  16.   void done();
  17.   void progress(const QString&, int, const QColor&);
  18.  
  19. public slots:
  20.   void doSomething();
  21.  
  22. private:
  23.  
  24.   int m_progress;
  25.   QMap<int, QString> m_states;
  26.   QTimer m_timer;
  27. };
  28.  
  29.  
  30. class MainWindow : public QMainWindow
  31. {
  32.     Q_OBJECT
  33.  
  34. public:
  35.     explicit MainWindow(QWidget *parent = 0);
  36.     ~MainWindow() {}
  37.     const DummyLoader* loader() const { return m_loader; }
  38.  
  39. public slots:
  40.     void startUpMaximized();
  41.     void lockPortraitOrientation();
  42.     void releaseOrientation();
  43.  
  44. private:
  45.     void removeContextMenus();
  46.  
  47. private:
  48.     int m_orientation;
  49.     DummyLoader* m_loader;
  50. };
  51.  
  52. #endif // MAINWINDOW_H

splashscreen.h
  1. #ifndef SPLASHSCREEN_H
  2. #define SPLASHSCREEN_H
  3.  
  4. #include <QSplashScreen>
  5.  
  6. class SplashScreen : public QSplashScreen
  7. {
  8.   Q_OBJECT
  9.  
  10. public:
  11.   explicit SplashScreen(bool blocking = false, const QPixmap & pixmap = QPixmap(), Qt::WindowFlags f = 0)
  12.     : QSplashScreen(pixmap,f), m_blocking(blocking) {}
  13.  
  14. protected: // reimp
  15.   void mousePressEvent ( QMouseEvent *event ) {
  16.     if(!m_blocking)
  17.       QSplashScreen::mousePressEvent(event);
  18.   }
  19.  
  20. private:
  21.   bool m_blocking;
  22.  
  23. };
  24.  
  25. #endif // SPLASHSCREEN_H

data.qrc

  1. <RCC>
  2.     <qresource prefix="/">
  3.         <file>images/splash.png</file>
  4.     </qresource>
  5. </RCC>

Also need to create a mainwindow.ui file using Qt Designer with dimensions 600×400

May 7, 2012

entricular entricular
Lab Rat
11 posts

To run this code see the directions provided below:

Create a main directory and inside of the directory created an images directory, store your created splash.png image inside of the images directory. Then copy all 5 files into the main directory and use Qt Creator to create a mainwindow.ui file with the dimensions of 600×400. Then run qmake -project, qmake, make. This application runs on Ubuntu Linux and Windows. However, I am trying to figure out how to maximize the main application window to fit the whole computer screen. At this time all it does is show the splashscreen for a few seconds then it kicks it out to a small window/box of the main application.

May 7, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts
I am trying to figure out how to maximize the main application window to fit the whole computer screen.

Try QWidget::resize(). Or use QWidget::setWindowState() with Qt::WindowMaximized or Qt::WindowFullScreen.

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

May 7, 2012

entricular entricular
Lab Rat
11 posts

Okay I went back and tweaked some of the code, I added the following lines to the main.cpp file

  1.  QObject::connect(w.loader(), SIGNAL(done()), &w, SLOT(startUpMaximized()));

It worked it kicked out the main application page to full screen. Look at line #30 in the main.cpp file.

So far I tested this out on Ubuntu Linux and Windows and it worked perfectly.

May 7, 2012

entricular entricular
Lab Rat
11 posts

One issue I can not figure out is why some coders refuse to post the #include directives and the full source code with their shared code, it is always snippets.

How else is newbie coder going to figure out how to use the shared code in their application? I find this very frustrating.

May 7, 2012

MuldeR MuldeR
Hobby Entomologist
813 posts

It’s probably because they want to point out a specific aspect and therefore paste the relevant lines.

Posting loads of code on a forum isn’t exactly what encourages people to post a reply. If you post your complete program and ask “why it isn’t working?” it will be pretty much impossible to give an useful answer. If, instead, you only post a small excerpt from your program – the specific part where you have a problem/question – then it will be much easier for other users to understand the issue and to give the desired reply…

Qt calls its header files exactly like the class they define; shouldn’t be too hard to figure out the right include ;)

 Signature 

My OpenSource software at: http://muldersoft.com/

Qt v4.8.6 MSVC 2013, static/shared: http://goo.gl/BXqhrS

Go visit the coop: http://youtu.be/Jay-fG9eaYk

Page  
1

  ‹‹ How does qHash(QStringRef&) work?      Combine floating QDockWidgets and into a single floating window with tabs? ››

You must log in to post a reply. Not a member yet? Register here!