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"
#include <QtSingleApplication>
 
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();
}
Category(s): Featured, Qt, Qt-Tips
Tags: , , ,

5 Responses to Create single instance application in Qt 4 : Qt Tip #1

  1. Cool tutorial ! Thank you.

    1 include is truncate in the tutorial. It is obviously:

    #include

    • No dear its include only. This is the way to include Qt Projects into other Qt Project. You’ve to add this in .pro file.

  2. Error in QObject::connect()…Ihave added the required lines to the .pro file…change the main.cpp file .

  3. please mention the required header files in main.cpp

Leave a Reply

Your email address will not be published. Required fields are marked *

*

 

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">