    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Using Qt's Non-GUI Classes</title>
        <link>https://members.accu.org/index.php/articles/803</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 17, #2 - Apr 2005</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c97/">172</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-97/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+97/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Using Qt's Non-GUI Classes</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 April 2005 13:16:11 +01:00 or Sun, 03 April 2005 13:16:11 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>In the fifth installment of our series on cross-platform programming with the Qt 3 C++ toolkit, we are going to review Qt's non-GUI classes.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>In the fifth installment of our series on cross-platform
programming with the Qt 3 C++ toolkit, we are going to review Qt's
non-GUI classes. Although Qt is fundamentally a GUI toolkit, it
contains many non-GUI-related classes that are useful when writing
portable applications. Here we'll focus on Qt's support for
networking, database access, inter-process communication, XML
handling and multithreading.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Network
Classes</h2>
</div>
<p>Qt provides a set of classes for writing cross-platform TCP/IP
clients and servers. The most important classes are <tt class=
"classname">QHttp</tt>, <tt class="classname">QFtp</tt>, <tt class=
"classname">QSocket</tt>, <tt class="classname">QSocketServer</tt>
and <tt class="classname">QSocketDevice</tt>.</p>
<p><tt class="classname">QHttp</tt> and <tt class=
"classname">QFtp</tt> implement the client side of the HTTP and FTP
protocols. HTTP (Hypertext Transfer Protocol) is an
application-level network protocol used mainly for downloading HTML
and XML files, but it is also used as a high-level transport
protocol for other types of data. For example, HTTP is often used
for transferring purchase orders over the Internet. In contrast,
FTP (File Transfer Protocol) is a protocol used almost exclusively
for browsing remote directories and transferring files. (see Figure
1.)</p>
<div class="figure"><a name="d0e49" id="d0e49"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/blanchette_protocol_stacks.png" align="middle" alt=
"HTTP and FTP protocol stacks"></div>
<p class="title c3">Figure 1. HTTP and FTP protocol stacks</p>
</div>
<p>Since the two protocols are used to solve similar problems, the
QHttp and QFtp classes have many features in common:</p>
<div class="variablelist">
<dl>
<dt><span class="term">Non-blocking behaviour.</span></dt>
<dd>
<p><tt class="classname">QHttp</tt> and <tt class=
"classname">QFtp</tt> are asynchronous. You can schedule a series
of commands (also called &quot;requests&quot; for HTTP). The commands are
executed later, when control goes back to Qt's event loop.
(Blocking behaviour is usually unacceptable in a GUI application,
because it can freeze the user interface for some time.)</p>
</dd>
<dt><span class="term">Command IDs.</span></dt>
<dd>
<p>Each command has a unique ID number that you can use to follow
the execution of the command. For example, <tt class=
"classname">QFtp</tt> emits the <tt class=
"methodname">commandStarted()</tt> and <tt class=
"methodname">commandFinished()</tt> signal with the command ID for
each command that is executed. <tt class="classname">QHttp</tt> has
<tt class="methodname">requestStarted()</tt> and <tt class=
"methodname">requestFinished()</tt> signals that work the same
way.</p>
</dd>
<dt><span class="term">Data transfer progress
indicators.</span></dt>
<dd>
<p><tt class="classname">QHttp</tt> and <tt class=
"classname">QFtp</tt> emit signals whenever data is transferred.
You can connect these signals to a progress bar's <tt class=
"methodname">setProgress()</tt> slot.</p>
</dd>
</dl>
</div>
<p>For example, let's assume we have a class called <tt class=
"classname">Downloader</tt> that has a <tt class=
"classname">QHttp</tt> data member called <tt class=
"varname">http</tt> and a <tt class="classname">QFile</tt> member
called <tt class="varname">outFile</tt>. To keep the example
simple, we'll do everything in the constructor and in a slot called
<tt class="methodname">httpDone()</tt>.</p>
<pre class="programlisting">
Downloader::Downloader() {
  outFile.setName(&quot;bookreviews.html&quot;);
  if(!outFile.open(IO_WriteOnly))
    return;
  connect(&amp;http, SIGNAL(done(bool)),
          this, SLOT(httpDone(bool)));
  http.setHost(&quot;www.accu.org&quot;);
  http.get(&quot;/bookreviews/public/&quot;, &amp;outFile);
  http.closeConnection();
}

void Downloader::httpDone(bool error) {
  if (error)
    ...
  outFile.close();
}
</pre>
<p>In the constructor, we open the output file. Then we connect
<tt class="classname">QHttp</tt>'s <tt class=
"methodname">done()</tt> signal to our <tt class=
"methodname">httpDone()</tt> slot. Finally we schedule three HTTP
requests: &quot;set host&quot;, &quot;get&quot;, and &quot;close connection&quot;. These requests
will be executed at some point in the future, when control returns
to Qt. When all three requests have been processed, the <tt class=
"methodname">httpDone()</tt> slot is called to close the file.</p>
<p>If you need TCP-based protocols other than HTTP and FTP (e.g.,
POP3, SMTP, NNTP or any proprietary protocol), you can use the
<tt class="classname">QSocket</tt> class to implement your own
protocol. TCP (Transmission Control Protocol) is a low-level
network protocol used by most Internet protocols, including HTTP
and FTP, for data transfer. It is a reliable, stream-oriented,
connection-oriented transport protocol. It is especially well
suited for continuous transmission of data.</p>
<p>An alternative to TCP is UDP (User Datagram Protocol). UDP is a
lightweight, unreliable, datagram-oriented, connectionless
protocol. It can be used when reliability isn't important. For
example, a server that reports the time of day could choose UDP. If
a datagram with the time of day is lost, the client can simply make
another request. UDP is supported through the <tt class=
"classname">QSocketDevice</tt> class.</p>
<div class="figure"><a name="d0e153" id="d0e153"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/blanchette_tcp_and_udp_protocols.png" align=
"middle" alt="TCP and UDP protocols"></div>
<p class="title c3">Figure 2. TCP and UDP protocols</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e159" id="d0e159"></a>Database
Classes</h2>
</div>
<p>The Qt database classes provide a multiplatform interface for
accessing SQL databases. Qt includes native drivers for Oracle,
Microsoft SQL Server, Sybase Adaptive Server, PostgreSQL, MySQL,
ODBC and SQLite. The drivers work on all platforms supported by Qt
and for which client libraries are available. Programs can access
multiple databases using multiple drivers simultaneously.</p>
<p>Programmers can easily execute any SQL statements. Qt also
provides a high-level C++ interface that programmers can use to
generate the appropriate SQL statements automatically.</p>
<p>The <tt class="classname">QSqlQuery</tt> class is used to
directly execute any SQL statement. It is also used to navigate the
result sets produced by <tt class="literal">SELECT</tt>
statements.</p>
<p>In the example below, a query is executed, and the result set
navigated using <tt class="methodname">QSqlQuery::next()</tt>:</p>
<pre class="programlisting">
QSqlQuery query(&quot;SELECT id, surname FROM staff&quot;);
while(query.next()) {
  cout &lt;&lt; &quot;id: &quot; &lt;&lt; query.value(0).toInt()
       &lt;&lt; &quot; surname: &quot; &lt;&lt; query.value(1).toString()
       &lt;&lt; endl;
}
</pre>
<p>Field values are indexed in the order they appear in the
<tt class="literal">SELECT</tt> statement. <tt class=
"classname">QSqlQuery</tt> also provides the <tt class=
"methodname">first()</tt>, <tt class="methodname">prev()</tt>,
<tt class="methodname">last()</tt> and <tt class=
"methodname">seek()</tt> navigation functions.</p>
<p><tt class="literal">INSERT</tt>, <tt class="literal">UPDATE</tt>
and <tt class="literal">DELETE</tt> are equally simple. Below is an
<tt class="literal">UPDATE</tt> example:</p>
<pre class="programlisting">
QSqlQuery query(&quot;UPDATE staff SET salary = salary&quot;
           &quot; * 1.10 WHERE id &gt; 1155 AND id &lt; 8155&quot;);
if(query.isActive()) {
  cout &lt;&lt; &quot;Pay rise given to &quot;
       &lt;&lt; query.numRowsAffected()
       &lt;&lt; &quot; staff&quot; &lt;&lt; endl;
}
</pre>
<p>Qt's SQL module also supports value binding and prepared
queries, for example:</p>
<pre class="programlisting">
QSqlQuery query;
query.prepare(&quot;INSERT INTO staff (id, surname,
                                  salary)&quot;
              &quot; VALUES (:id, :surname, :salary)&quot;

query.bindValue(&quot;:id&quot;, 8120);
query.bindValue(&quot;:surname&quot;, &quot;Bean&quot;);
query.bindValue(&quot;:salary&quot;, 29960.5);
query.exec();
</pre>
<p>Value binding can be achieved using named binding and named
placeholders (as above), or using positional binding with named or
positional placeholders. Qt's binding syntax works with all
supported databases, either using the underlying database support
or by emulation.</p>
<p>For programmers who are not comfortable writing raw SQL, the
<tt class="classname">QSqlCursor</tt> class provides a high-level
interface for browsing and editing records in SQL tables or views
without the need to write SQL statements. For example:</p>
<pre class="programlisting">
QSqlCursor cur(&quot;staff&quot;);
while(cur.next()) {
  cout &lt;&lt; &quot;id: &quot; &lt;&lt; cur.value(&quot;id&quot;).toInt()
       &lt;&lt; &quot; surname: &quot;
       &lt;&lt; cur.value(&quot;surname&quot;).toString() &lt;&lt; endl;
}
</pre>
<p><tt class="classname">QSqlCursor</tt> also supports the ordering
and filtering that are achieved using the <tt class="literal">ORDER
BY</tt> and <tt class="literal">WHERE</tt> clauses in SQL
statements.</p>
<p>Database drivers usually supply data as strings, regardless of
the actual datatype. Qt handles such data seamlessly using the
<tt class="classname">QVariant</tt> class. Database drivers can be
asked about the features they support, including query-size
reporting and transactions. The <tt class=
"methodname">transaction()</tt>, <tt class=
"methodname">commit()</tt> and <tt class=
"methodname">rollback()</tt> functions can be used if the database
supports transactions.</p>
<p>Qt also provides classes that make it easy to present data from
the database to the user. One of them is <tt class=
"classname">QDataTable</tt>, a table widget that displays records
from a result set (see Figure 3). <tt class=
"classname">QDataTable</tt> supports in-place editing. Records can
be updated and deleted without writing any code. Insertions require
some code since most database designs expect new records to be
created with a unique key.</p>
<div class="figure"><a name="d0e261" id="d0e261"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/blanchette_qdatatable.png" align="middle" alt=
"QDataTable"></div>
<p class="title c3">Figure 3. QDataTable</p>
</div>
<p>Qt also includes <tt class="classname">QDataBrowser</tt> and
<tt class="classname">QDataView</tt> to display records as forms
(see Figure 4), typically with one or perhaps a few records shown
at a time. These classes provide buttons with ready-made
connections for navigating through the records. <tt class=
"classname">QDataView</tt> is used for read-only data. <tt class=
"classname">QDataBrowser</tt> is used for editing, and can provide
ready-made insert, update and delete buttons.</p>
<div class="figure"><a name="d0e281" id="d0e281"></a>
<div class="mediaobject c2"><img src=
"/var/uploads/journals/resources/blanchette_qdatabrowser.png" align="middle" alt=
"QDataBrowser"></div>
<p class="title c3">Figure 4. QDataBrowser</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e287" id="d0e287"></a>Inter-Process
Communication</h2>
</div>
<p>The <tt class="classname">QProcess</tt> class is used to start
external programs, and to communicate with them from a Qt
application in a platform-independent way. Communication is
achieved by writing to the external program's standard input stream
and by reading its standard output and standard error.</p>
<p><tt class="classname">QProcess</tt> works asynchronously,
reporting the availability of data by emitting Qt signals. We can
connect to the signals to retrieve and process the data, and
optionally respond by sending data back to the external
program.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e299" id="d0e299"></a>XML
Classes</h2>
</div>
<p>Qt's XML module provides a SAX parser and a DOM parser, both of
which read well-formed XML and are non-validating. The SAX (Simple
API for XML) implementation follows the design of the SAX2 Java
implementation, with adapted naming conventions. The DOM (Document
Object Model) Level 2 implementation follows the W3C recommendation
and includes namespace support.</p>
<p>Many Qt applications use XML format to store their persistent
data. The SAX parser is used for reading data incrementally and is
especially suitable both for simple parsing requirements and for
very large files. The DOM parser reads the entire file into a tree
structure in memory that can be traversed at will.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e306" id="d0e306"></a>Multithreaded
Programming</h2>
</div>
<p>GUI applications often use multiple threads: one thread to keep
the user interface responsive, and one or many other threads to
perform time-consuming activities such as reading large files and
performing complex calculations. Qt can be configured to support
multithreading, and provides four central threading classes:
<tt class="classname">QThread</tt>, <tt class=
"classname">QMutex</tt>, <tt class="classname">QSemaphore</tt> and
<tt class="classname">QWaitCondition</tt>.</p>
<p>To create a thread, subclass <tt class="classname">QThread</tt>
and reimplement its run() function. For example:</p>
<pre class="programlisting">
class MyThread : public QThread {
protected:
  void run();
};

void MyThread::run() {
  ... // thread code goes here
}
</pre>
<p>Then, create an instance of the thread object and call
<tt class="methodname">QThread::start()</tt>. The code that appears
in the <tt class="methodname">run()</tt> reimplementation will then
be executed in a separate thread.</p>
<p>The <tt class="classname">QMutex</tt> class provides a means of
protecting a variable or a piece of code so that only one thread
can access it at a time, preventing memory corruption, crashes or
other race conditions. The class provides a lock() function that
locks the mutex. If the mutex is unlocked, the current thread
seizes it immediately and locks it; otherwise, the current thread
is blocked until the thread that holds the mutex unlocks it. Either
way, when the call to <tt class="methodname">lock()</tt> returns,
the current thread holds the mutex until it calls <tt class=
"methodname">unlock()</tt>. For example:</p>
<pre class="programlisting">
QString globalString;
QMutex mutex;
...
mutex.lock();
globalString += &quot;More text\n&quot;;
mutex.unlock();
</pre>
<p><tt class="classname">QSemaphore</tt> and <tt class=
"classname">QWaitCondition</tt> are two other classes that make it
possible to synchronize threads.</p>
<p>This article presented a short overview of some of the most
interesting non-GUI classes offered by Qt. There are many more
classes than we presented here. For example, Qt has a Unicode
16-bit <tt class="classname">QString</tt> data type, classes for
performing text and binary I/O, classes for supporting
internationalisation, and more.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
