Home

A Trivial Example

The application in this example has a log-view that displays messages sent by further instances of the same application.

The example demonstrates the use of the QtSingleApplication class to detect and communicate with a running instance of the application using the sendMessage() API. The messageReceived() signal is used to display received messages in a QTextEdit log.

    #include <qtsingleapplication.h>
    #include <qtextview.h>

    int main(int argc, char **argv)
    {
        QtSingleApplication instance("QtSingleApplication Trivial Example", argc, argv);
The example has only the main entry point function. A QtSingleApplication object is created immediately, passing a unique ID string and the command line parameters as received by the main function to the constructor.

        if (instance.sendMessage("Wake up!"))
            return 0;
If the message could be sent, i.e. if another instance of this application is already running, the started process exits immediately.

        instance.initialize();

        QTextView logview;
        logview.show();
Otherwise the instance calls initialize(), and creates the user interface.

        QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
                         &logview, SLOT(append(const QString&)));

        instance.setMainWidget(&logview);
The messageReceived() signal is connected to the QTextEdit's append() slot. Every message received from further instances of this application will be display in the log.

The logview object is also set as the application's main widget. Everytime a message is received the window will be activated.

        return instance.exec();
    }
Finally the event loop is entered.
Copyright © 2003-2006 TrolltechTrademarks
Qt Solutions