Create single instance application in Qt 4 : Qt Tip #1

Qt Tip #1
Many times we want only single instance of application. How can we achieve this. I’m going to show a simple way to achieve this.

We need a Utility that is freely provided by Qt guys . Click here to know more qtsingleapplication
Download zip version of this utility from here

Extract file from zip into your project folder. Rename folder whatever you want.
Open .pro file (Qt Project file) add these lines there

include(qtsingleapplicationfolder\src\qtsingleapplication.pri)

ofcourse use your folder name instead of qtsingleapplicationfolder.

You will see, some are files added in project explorer. Open your main.cpp and modify like this

/*
Credit : Yash Bhardwaj
Site :  mvclogic.com
License: Don't remove this sticker else totally FREE
*/
 
#include
#include "mainwindow.h"
 
int main(int argc, char *argv[])
{
 
    QtSingleApplication instance(argc, argv);
 
   QString message=argv[1];
 
  if (instance.sendMessage(message))
         return 0;
 
     MainWindow mw;
 
     /*In next tip I'll cover this function . This function
       communicate between different instance of application.
        Such a thing will used to open many file in single editor.
 
        if(message.length()>0)
        mw.handleMessage(message);
    hang on guys....
   */
 
     mw.show();
 
     QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
                      &mw, SLOT(handleMessage(const QString&)));
 
    /* instance.setActivationWindow(&mw, false);
     QObject::connect(&mw, SIGNAL(needToShow()),
    &instance, SLOT(activateWindow()));*/
 
    QGTKSTYLE_H
    return instance.exec();
}

Popularity: 55% [?]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

Oct25

Leave a Reply