<p>The user interface in this application is a <ahref="http://qt.nokia.com/doc/4.6/qmainwindow.html">QMainWindow</a> subclass with a <ahref="http://qt.nokia.com/doc/4.6/qmdiarea.html">QMdiArea</a> as the central widget. It implements a slot <tt>handleMessage()</tt> that will be connected to the messageReceived() signal of the <ahref="qtsingleapplication.html">QtSingleApplication</a> class.</p>
<pre> MainWindow::MainWindow()
{
workspace = new QMdiArea(this);
setCentralWidget(workspace);
}</pre>
<p>The <ahref="http://qt.nokia.com/doc/4.6/designer-to-know.html">MainWindow</a> constructor creates a minimal user interface.</p>
if (message.toLower().startsWith("/print ")) {
filename = filename.mid(7);
action = Print;
} else if (!message.isEmpty()) {
action = Open;
}
if (action == Nothing) {
emit needToShow();
return;
}
QFile file(filename);
QString contents;
if (file.open(QIODevice::ReadOnly))
contents = file.readAll();
else
contents = "[[Error: Could not load file " + filename + "]]";
QTextEdit *view = new QTextEdit;
view->setPlainText(contents);
switch(action) {</pre>
<p>The handleMessage() slot interprets the message passed in as a filename that can be prepended with <i>/print</i> to indicate that the file should just be printed rather than loaded.</p>
<pre> case Print:
{
QPrinter printer;
view->print(&printer);
delete view;
}
break;
case Open:
{
workspace->addSubWindow(view);
view->setWindowTitle(message);
view->show();
emit needToShow();
}
break;
default:
break;
};
}</pre>
<p>Loading the file will also activate the window.</p>
<p>The <tt>main</tt> entry point function creates a <ahref="qtsingleapplication.html">QtSingleApplication</a> object, and creates a message to send to a running instance of the application. If the message was sent successfully the process exits immediately.</p>
<p>If the message could not be sent the application starts up. Note that <tt>false</tt> is passed to the call to setActivationWindow() to prevent automatic activation for every message received, e.g. when the application should just print a file. Instead, the message handling function determines whether activation is requested, and signals that by emitting the needToShow() signal. This is then simply connected directly to <ahref="qtsingleapplication.html">QtSingleApplication</a>'s activateWindow() slot.</p>