Sophie

Sophie

distrib > Fedora > 18 > x86_64 > by-pkgid > ff187cb994c94c614ecc64c5a8528b1b > files > 1702

qt-doc-4.8.5-10.fc18.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- gettingstartedqml.qdoc -->
  <title>Qt 4.8: Getting Started Programming with QML</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script src="scripts/jquery.js" type="text/javascript"></script>
  <script src="scripts/functions.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />
  <!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->

<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>

</head>
<body class="" onload="CheckEmptyAndLoadList();">
 <div class="header" id="qtdocheader">
    <div class="content"> 
    <div id="nav-logo">
      <a href="index.html">Home</a></div>
    <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
    <div id="narrowsearch"></div>
    <div id="nav-topright">
      <ul>
        <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
        <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
        <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
          DOC</a></li>
        <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
      </ul>
    </div>
    <div id="shortCut">
      <ul>
        <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
        <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS        </a></li>
      </ul>
     </div>
 <ul class="sf-menu" id="narrowmenu"> 
             <li><a href="#">API Lookup</a> 
                 <ul> 
                     <li><a href="classes.html">Class index</a></li> 
           <li><a href="functions.html">Function index</a></li> 
           <li><a href="modules.html">Modules</a></li> 
           <li><a href="namespaces.html">Namespaces</a></li> 
           <li><a href="qtglobal.html">Global Declarations</a></li> 
           <li><a href="qdeclarativeelements.html">QML elements</a></li> 
             </ul> 
             </li> 
             <li><a href="#">Qt Topics</a> 
                 <ul> 
                        <li><a href="qt-basic-concepts.html">Programming with Qt</a></li>  
                        <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li>  
                        <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>  
                        <li><a href="supported-platforms.html">Supported Platforms</a></li>  
                        <li><a href="technology-apis.html">Qt and Key Technologies</a></li>  
                        <li><a href="best-practices.html">How-To's and Best Practices</a></li>  
              </ul> 
                 </li> 
                 <li><a href="#">Examples</a> 
                     <ul> 
                       <li><a href="all-examples.html">Examples</a></li> 
                       <li><a href="tutorials.html">Tutorials</a></li> 
                       <li><a href="demos.html">Demos</a></li> 
                       <li><a href="qdeclarativeexamples.html">QML Examples</a></li> 
                </ul> 
                     </li> 
                 </ul> 
    </div>
  </div>
  <div class="wrapper">
    <div class="hd">
      <span></span>
    </div>
    <div class="bd group">
      <div class="sidebar">
        <div class="searchlabel">
          Search index:</div>
        <div class="search" id="sidebarsearch">
          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />
 <div id="resultdialog"> 
 <a href="#" id="resultclose">Close</a> 
 <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> 
 <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> 
 <ul id="resultlist" class="all"> 
 </ul> 
 </div> 
            </fieldset>
          </form>
        </div>
        <div class="box first bottombar" id="lookup">
          <h2 title="API Lookup"><span></span>
            API Lookup</h2>
          <div  id="list001" class="list">
          <ul id="ul001" >
              <li class="defaultLink"><a href="classes.html">Class index</a></li>
              <li class="defaultLink"><a href="functions.html">Function index</a></li>
              <li class="defaultLink"><a href="modules.html">Modules</a></li>
              <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
              <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
              <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
            </ul> 
          </div>
        </div>
        <div class="box bottombar" id="topics">
          <h2 title="Qt Topics"><span></span>
            Qt Topics</h2>
          <div id="list002" class="list">
            <ul id="ul002" >
               <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> 
               <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> 
               <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> 
               <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>  
               <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> 
               <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> 
            </ul>  
          </div>
        </div>
        <div class="box" id="examples">
          <h2 title="Examples"><span></span>
            Examples</h2>
          <div id="list003" class="list">
        <ul id="ul003">
              <li class="defaultLink"><a href="all-examples.html">Examples</a></li>
              <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
              <li class="defaultLink"><a href="demos.html">Demos</a></li>
              <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
            </ul> 
          </div>
        </div>
      </div>
      <div class="wrap">
        <div class="toolbar">
          <div class="breadcrumb toolblock">
            <ul>
              <li class="first"><a href="index.html">Home</a></li>
              <!--  Breadcrumbs go here -->
<li>Getting Started Programming with QML</li>
            </ul>
          </div>
          <div class="toolbuttons toolblock">
            <ul>
              <li id="smallA" class="t_button">A</li>
              <li id="medA" class="t_button active">A</li>
              <li id="bigA" class="t_button">A</li>
              <li id="print" class="t_button"><a href="javascript:this.print();">
                <span>Print</span></a></li>
            </ul>
        </div>
        </div>
        <div class="content mainContent">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#installation">Installation</a></li>
<li class="level1"><a href="#qml-to-build-user-interfaces">QML to Build User Interfaces</a></li>
<li class="level1"><a href="#defining-a-button-and-a-menu">Defining a Button and a Menu</a></li>
<li class="level2"><a href="#basic-component-a-button">Basic Component - a Button</a></li>
<li class="level2"><a href="#creating-a-menu-page">Creating a Menu Page</a></li>
<li class="level1"><a href="#implementing-a-menu-bar">Implementing a Menu Bar</a></li>
<li class="level2"><a href="#using-data-models-and-views">Using Data Models and Views</a></li>
<li class="level1"><a href="#building-a-text-editor">Building a Text Editor</a></li>
<li class="level2"><a href="#declaring-a-textarea">Declaring a TextArea</a></li>
<li class="level2"><a href="#combining-components-for-the-text-editor">Combining Components for the Text Editor</a></li>
<li class="level1"><a href="#decorating-the-text-editor">Decorating the Text Editor</a></li>
<li class="level2"><a href="#implementing-a-drawer-interface">Implementing a Drawer Interface</a></li>
<li class="level3"><a href="#where-to-go-from-here">Where to Go from Here</a></li>
<li class="level2"><a href="#extending-qml-using-qt-c">Extending QML using Qt C++</a></li>
<li class="level3"><a href="#exposing-c-classes-to-qml">Exposing C++ Classes to QML</a></li>
<li class="level3"><a href="#building-a-qt-plugin">Building a Qt Plugin</a></li>
<li class="level3"><a href="#registering-a-class-into-qml">Registering a Class into QML</a></li>
<li class="level3"><a href="#creating-qml-properties-in-a-c-class">Creating QML Properties in a C++ class</a></li>
<li class="level3"><a href="#importing-a-plugin-in-qml">Importing a Plugin in QML</a></li>
<li class="level3"><a href="#integrating-a-file-dialog-into-the-file-menu">Integrating a File Dialog into the File Menu</a></li>
<li class="level2"><a href="#text-editor-completion">Text Editor Completion</a></li>
<li class="level1"><a href="#running-the-text-editor">Running the Text Editor</a></li>
</ul>
</div>
<h1 class="title">Getting Started Programming with QML</h1>
<span class="subtitle"></span>
<!-- $$$gettingstartedqml.html-description -->
<div class="descr"> <a name="details"></a>
<p>Welcome to the world of QML, the declarative UI language. In this Getting Started guide, we will create a simple text editor application using QML. After reading this guide, you should be ready to develop your own applications using QML and Qt C++.</p>
<a name="installation"></a>
<h2>Installation</h2>
<p>First, we would need to install the latest version of Qt that includes <a href="qtquick.html">Qt Quick</a>, which is Qt 4.7&#x2e; The <a href="installation.html">installation</a> guide contains installation instructions and requirements for different platforms.</p>
<p>Qt Quick includes a declarative language called <a href="qdeclarativeintroduction.html">QML</a>, the <a href="qtdeclarative.html">Qt Declarative Module</a>, and <a href="qmlviewer.html">QML Viewer</a>.</p>
<a name="qml-to-build-user-interfaces"></a>
<h2>QML to Build User Interfaces</h2>
<p>The application we are building is a simple text editor that will load, save, and perform some text manipulation. This guide will consist of two parts. The first part will involve designing the application layout and behaviors using declarative language in QML. For the second part, file loading and saving will be implemented using Qt C++. Using <a href="metaobjects.html">Qt's Meta-Object System</a>, we can expose C++ functions as properties that QML elements can use. Utilizing QML and Qt C++, we can efficiently decouple the interface logic from the application logic.</p>
<p class="centerAlign"><img src="images/qml-texteditor5_editmenu.png" alt="" /></p><p>The final source code is in the <tt>examples/tutorials/gettingStarted/gsQml</tt> directory. You may need to compile the C++ plugin in the <tt>examples/tutorials/gettingStarted/gsQml/</tt> first. This will put the C++ plugin in a directory where the QML files may find it.</p>
<p>To launch the text editor, merely provide the included <a href="qmlviewer.html">qmlviewer</a> tool with the QML file as the argument. The C++ portion of this tutorial assumes that the reader possesses basic knowledge of Qt's compilation procedures.</p>
<p>Tutorial chapters:</p>
<ol class="1">
<li><a href="#defining-a-button-and-a-menu">Defining a Button and a Menu</a></li>
<li><a href="#implementing-a-menu-bar">Implementing a Menu Bar</a></li>
<li><a href="#building-a-text-editor">Building a Text Editor</a></li>
<li><a href="#decorating-the-text-editor">Decorating the Text Editor</a></li>
<li><a href="#extending-qml-using-qt-c">Extending QML using Qt C++</a></li>
</ol>
<a name="defining-a-button-and-a-menu"></a>
<h2>Defining a Button and a Menu</h2>
<a name="basic-component-a-button"></a>
<h3>Basic Component - a Button</h3>
<p>We start our text editor by building a button. Functionally, a button has a mouse sensitive area and a label. Buttons perform actions when a user presses the button.</p>
<p>In QML, the basic visual item is the <a href="qml-rectangle.html">Rectangle</a> element. The <tt>Rectangle</tt> element has properties to control the element's appearance and location.</p>
<pre class="qml"> import QtQuick 1.0

 <span class="type"><a href="qml-rectangle.html">Rectangle</a></span> {
     <span class="name">id</span>: <span class="name">simplebutton</span>
     <span class="name">color</span>: <span class="string">&quot;grey&quot;</span>
     <span class="name">width</span>: <span class="number">150</span>; <span class="name">height</span>: <span class="number">75</span>

     <span class="type"><a href="qml-text.html">Text</a></span>{
         <span class="name">id</span>: <span class="name">buttonLabel</span>
         <span class="name">anchors</span>.centerIn: <span class="name">parent</span>
         <span class="name">text</span>: <span class="string">&quot;button label&quot;</span>
     }
 }</pre>
<p>First, the <tt>import QtQuick 1.0</tt> allows the qmlviewer tool to import the QML elements we will later use. This line must exist for every QML file. Notice that the version of Qt modules is included in the import statement.</p>
<p>This simple rectangle has a unique identifier, <tt>simplebutton</tt>, which is bound to the id property. The <tt>Rectangle</tt> element's properties are bound to values by listing the property, followed by a colon, then the value. In the code sample, the color <tt>grey</tt> is bound to the the Rectangle's <tt>color</tt> property. Similarly, we bind the <tt>width</tt> and <tt>height</tt> of the Rectangle.</p>
<p>The <a href="qml-text.html">Text</a> element is a non-editable text field. We name this <tt>Text</tt> element <tt>buttonLabel</tt>. To set the string content of the Text field, we bind a value to the <tt>text</tt> property. The label is contained within the Rectangle and in order to center it in the middle, we assign the <tt>anchors</tt> of the Text element to its parent, which is called <tt>simplebutton</tt>. Anchors may bind to other items' anchors, allowing layout assignments simpler.</p>
<p>We shall save this code as <tt>SimpleButton.qml</tt>. Running qmlviewer with the file as the argument will display the grey rectangle with a text label.</p>
<p class="centerAlign"><img src="images/qml-texteditor1_simplebutton.png" alt="" /></p><p>To implement the button click functionality, we can use QML's event handling. QML's event handling is very similar to <a href="signalsandslots.html">Qt's signal and slot</a> mechanism. Signals are emitted and the connected slot is called.</p>
<pre class="cpp"> Rectangle{
     id:simplebutton
     <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>

     MouseArea{
         id: buttonMouseArea

         anchors<span class="operator">.</span>fill: parent <span class="comment">//anchor all sides of the mouse area to the rectangle's anchors</span>
                 <span class="comment">//onClicked handles valid mouse button clicks</span>
         onClicked: console<span class="operator">.</span>log(buttonLabel<span class="operator">.</span>text <span class="operator">+</span> <span class="string">&quot; clicked&quot;</span> )
     }
 }</pre>
<p>We include a <a href="qml-mousearea.html">MouseArea</a> element in our simplebutton. <tt>MouseArea</tt> elements describe the interactive area where mouse movements are detected. For our button, we anchor the whole <a href="qml-mousearea.html">MouseArea</a> to its parent, which is <tt>simplebutton</tt>. The <tt>anchors.fill</tt> syntax is one way of accessing a specific property called <tt>fill</tt> inside a group of properties called <tt>anchors</tt>. QML uses <a href="qml-anchor-layout.html">anchor-based layouts</a> where items can anchor to another item, creating robust layouts.</p>
<p>The <tt>MouseArea</tt> has many signal handlers that are called during mouse movements within the specified <tt>MouseArea</tt> boundaries. One of them is <tt>onClicked</tt> and it is called whenever the acceptable mouse button is clicked, the left click being the default. We can bind actions to the onClicked handler. In our example, <tt>console.log()</tt> outputs text whenever the mouse area is clicked. The function <tt>console.log()</tt> is a useful tool for debugging purposes and for outputting text.</p>
<p>The code in <tt>SimpleButton.qml</tt> is sufficient to display a button on the screen and output text whenever it is clicked with a mouse.</p>
<pre class="cpp"> Rectangle {
     id: button
     <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>

     property color buttonColor: <span class="string">&quot;lightblue&quot;</span>
     property color onHoverColor: <span class="string">&quot;gold&quot;</span>
     property color borderColor: <span class="string">&quot;white&quot;</span>

     signal buttonClick()
     onButtonClick: {
         console<span class="operator">.</span>log(buttonLabel<span class="operator">.</span>text <span class="operator">+</span> <span class="string">&quot; clicked&quot;</span> )
     }

     MouseArea{
         onClicked: buttonClick()
         hoverEnabled: <span class="keyword">true</span>
         onEntered: parent<span class="operator">.</span>border<span class="operator">.</span>color <span class="operator">=</span> onHoverColor
         onExited:  parent<span class="operator">.</span>border<span class="operator">.</span>color <span class="operator">=</span> borderColor
     }

     <span class="comment">//determines the color of the button by using the conditional operator</span>
     color: buttonMouseArea<span class="operator">.</span>pressed <span class="operator">?</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">.</span>darker(buttonColor<span class="operator">,</span> <span class="number">1.5</span>) : buttonColor
 }</pre>
<p>A fully functioning button is in <tt>Button.qml</tt>. The code snippets in this article have some code omitted, denoted by ellipses because they were either introduced earlier in the previous sections or irrelevant to the current code discussion.</p>
<p>Custom properties are declared using the <tt>property type name</tt> syntax. In the code, the property <tt>buttonColor</tt>, of type <tt>color</tt>, is declared and bound to the value <tt>&quot;lightblue&quot;</tt>. The <tt>buttonColor</tt> is later used in a conditional operation to determine the buttons's fill color. Note that property value assignment is possible using the <tt>=</tt> equals sign, in addition to value binding using the <tt>:</tt> colon character. Custom properties allow internal items to be accessible outside of the Rectangle's scope. There are basic <a href="qdeclarativebasictypes.html">QML types</a> such as <tt>int</tt>, <tt>string</tt>, <tt>real</tt>, as well as a type called <tt>variant</tt>.</p>
<p>By binding the <tt>onEntered</tt> and <tt>onExited</tt> signal handlers to colors, the button's border will turn yellow when the mouse hovers above the button and reverts the color when the mouse exits the mouse area.</p>
<p>A <tt>buttonClick()</tt> signal is declared in <tt>Button.qml</tt> by placing the <tt>signal</tt> keyword in front of the signal name. All signals have their handlers automatically created, their names starting with <tt>on</tt>. As a result, the <tt>onButtonClick</tt> is <tt>buttonClick</tt>'s handler. The <tt>onButtonClick</tt> is then assigned an action to perform. In our button example, the <tt>onClicked</tt> mouse handler will simply call <tt>onButtonClick</tt>, which displays a text. The <tt>onButtonClick</tt> enables outside objects to access the <tt>Button</tt>'s mouse area easily. For example, items may have more than one <tt>MouseArea</tt> declarations and a <tt>buttonClick</tt> signal can make the distinction between the several <tt>MouseArea</tt> signal handlers better.</p>
<p>We now have the basic knowledge to implement items in QML that can handle basic mouse movements. We created a <tt>Text</tt> label inside a <tt>Rectangle</tt>, customized its properties, and implemented behaviors that respond to mouse movements. This idea of creating elements within elements is repeated throughout the text editor application.</p>
<p>This button is not useful unless used as a component to perform an action. In the next section, we will soon create a menu containing several of these buttons.</p>
<p class="centerAlign"><img src="images/qml-texteditor1_button.png" alt="" /></p><a name="creating-a-menu-page"></a>
<h3>Creating a Menu Page</h3>
<p>Up to this stage, we covered how to create elements and assign behaviors inside a single QML file. In this section, we will cover how to import QML elements and how to reuse some of the created components to build other components.</p>
<p>Menus display the contents of a list, each item having the ability to perform an action. In QML, we can create a menu in several ways. First, we will create a menu containing buttons which will eventually perform different actions. The menu code is in <tt>FileMenu.qml</tt>.</p>
<pre class="cpp"> import <span class="type">QtQuick</span> <span class="number">1.0</span>                \\import the main <span class="type"><a href="qt.html">Qt</a></span> QML module
 import <span class="string">&quot;folderName&quot;</span>            \\import the contents of the folder
 import <span class="string">&quot;script.js&quot;</span> as Script        \\import a Javascript file <span class="keyword">and</span> name it as Script</pre>
<p>The syntax shown above shows how to use the <tt>import</tt> keyword. This is required to use JavaScript files, or QML files that are not within the same directory. Since <tt>Button.qml</tt> is in the same directory as <tt>FileMenu.qml</tt>, we do not need to import the <tt>Button.qml</tt> file to use it. We can directly create a <tt>Button</tt> element by declaring <tt>Button{}</tt>, similar to a <tt>Rectangle{}</tt> declaration.</p>
<pre class="cpp"> In FileMenu<span class="operator">.</span>qml:

     Row{
         anchors<span class="operator">.</span>centerIn: parent
         spacing: parent<span class="operator">.</span>width<span class="operator">/</span><span class="number">6</span>

         Button{
             id: loadButton
             buttonColor: <span class="string">&quot;lightgrey&quot;</span>
             label: <span class="string">&quot;Load&quot;</span>
         }
         Button{
             buttonColor: <span class="string">&quot;grey&quot;</span>
             id: saveButton
             label: <span class="string">&quot;Save&quot;</span>
         }
         Button{
             id: exitButton
             label: <span class="string">&quot;Exit&quot;</span>
             buttonColor: <span class="string">&quot;darkgrey&quot;</span>

             onButtonClick: <span class="type"><a href="qt.html">Qt</a></span><span class="operator">.</span>quit()
         }
     }</pre>
<p>In <tt>FileMenu.qml</tt>, we declare three <tt>Button</tt> elements. They are declared inside a <a href="qml-row.html">Row</a> element, a positioner that will position its children along a vertical row. The <tt>Button</tt> declaration resides in Button.qml, which is the same as the <tt>Button.qml</tt> we used in the previous section. New property bindings can be declared within the newly created buttons, effectively overwriting the properties set in <tt>Button.qml</tt>. The button called <tt>exitButton</tt> will quit and close the window when it is clicked. Note that the signal handler <tt>onButtonClick</tt> in <tt>Button.qml</tt> will be called in addition to the <tt>onButtonClick</tt> handler in <tt>exitButton</tt>.</p>
<p class="centerAlign"><img src="images/qml-texteditor1_filemenu.png" alt="" /></p><p>The <tt>Row</tt> declaration is declared in a <tt>Rectangle</tt>, creating a rectangle container for the row of buttons. This additional rectangle creates an indirect way of organizing the row of buttons inside a menu.</p>
<p>The declaration of the edit menu is very similar at this stage. The menu has buttons that have the labels: <tt>Copy</tt>, <tt>Paste</tt>, and <tt>Select All</tt>.</p>
<p class="centerAlign"><img src="images/qml-texteditor1_editmenu.png" alt="" /></p><p>Armed with our knowledge of importing and customizing previously made components, we may now combine these menu pages to create a menu bar, consisting of buttons to select the menu, and look at how we may structure data using QML.</p>
<a name="implementing-a-menu-bar"></a>
<h2>Implementing a Menu Bar</h2>
<p>Our text editor application will need a way to display menus using a menu bar. The menu bar will switch the different menus and the user can choose which menu to display. Menu switching implies that the menus need more structure than merely displaying them in a row. QML uses models and views to structure data and display the structured data.</p>
<a name="using-data-models-and-views"></a>
<h3>Using Data Models and Views</h3>
<p>QML has different <a href="qdeclarativemodels.html">data views</a> that display <a href="qdeclarativemodels.html">data models</a>. Our menu bar will display the menus in a list, with a header that displays a row of menu names. The list of menus are declared inside a <tt>VisualItemModel</tt>. The <a href="qml-visualitemmodel.html"><tt>VisualItemModel</tt></a> element contains items that already have views such as <tt>Rectangle</tt> elements and imported UI elements. Other model types such as the <a href="qml-listmodel.html"><tt>ListModel</tt></a> element need a delegate to display their data.</p>
<p>We declare two visual items in the <tt>menuListModel</tt>, the <tt>FileMenu</tt> and the <tt>EditMenu</tt>. We customize the two menus and display them using a <a href="qml-listview.html">ListView</a>. The <tt>MenuBar.qml</tt> file contains the QML declarations and a simple edit menu is defined in <tt>EditMenu.qml</tt>.</p>
<pre class="cpp">     VisualItemModel{
         id: menuListModel
         FileMenu{
             width: menuListView<span class="operator">.</span>width
             height: menuBar<span class="operator">.</span>height
             color: fileColor
         }
         EditMenu{
             color: editColor
             width:  menuListView<span class="operator">.</span>width
             height: menuBar<span class="operator">.</span>height
         }
     }</pre>
<p>The <a href="qml-listview.html">ListView</a> element will display a model according to a delegate. The delegate may declare the model items to display in a <tt>Row</tt> element or display the items in a grid. Our <tt>menuListModel</tt> already has visible items, therefore, we do not need to declare a delegate.</p>
<pre class="cpp">     ListView{
         id: menuListView

         <span class="comment">//Anchors are set to react to window anchors</span>
         anchors<span class="operator">.</span>fill:parent
         anchors<span class="operator">.</span>bottom: parent<span class="operator">.</span>bottom
         width:parent<span class="operator">.</span>width
         height: parent<span class="operator">.</span>height

         <span class="comment">//the model contains the data</span>
         model: menuListModel

         <span class="comment">//control the movement of the menu switching</span>
         snapMode: ListView<span class="operator">.</span>SnapOneItem
         orientation: ListView<span class="operator">.</span>Horizontal
         boundsBehavior: Flickable<span class="operator">.</span>StopAtBounds
         flickDeceleration: <span class="number">5000</span>
         highlightFollowsCurrentItem: <span class="keyword">true</span>
         highlightMoveDuration:<span class="number">240</span>
         highlightRangeMode: ListView<span class="operator">.</span>StrictlyEnforceRange
     }</pre>
<p>Additionally, <tt>ListView</tt> inherits from <a href="qml-flickable.html"><tt>Flickable</tt></a>, making the list respond to mouse drags and other gestures. The last portion of the code above sets <tt>Flickable</tt> properties to create the desired flicking movement to our view. In particular,the property <tt>highlightMoveDuration</tt> changes the duration of the flick transition. A higher <tt>highlightMoveDuration</tt> value results in slower menu switching.</p>
<p>The <tt>ListView</tt> maintains the model items through an <tt>index</tt> and each visual item in the model is accessible through the <tt>index</tt>, in the order of the declaration. Changing the <tt>currentIndex</tt> effectively changes the highlighted item in the <tt>ListView</tt>. The header of our menu bar exemplify this effect. There are two buttons in a row, both changing the current menu when clicked. The <tt>fileButton</tt> changes the current menu to the file menu when clicked, the <tt>index</tt> being <tt>0</tt> because <tt>FileMenu</tt> is declared first in the <tt>menuListModel</tt>. Similarly, the <tt>editButton</tt> will change the current menu to the <tt>EditMenu</tt> when clicked.</p>
<p>The <tt>labelList</tt> rectangle has <tt>z</tt> value of <tt>1</tt>, denoting that it is displayed at the front of the menu bar. Items with higher <tt>z</tt> values are displayed in front of items with lower <tt>z</tt> values. The default <tt>z</tt> value is <tt>0</tt>.</p>
<pre class="cpp">     Rectangle{
         id: labelList
         <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
         z: <span class="number">1</span>
         Row{
             anchors<span class="operator">.</span>centerIn: parent
             spacing:<span class="number">40</span>
             Button{
                 label: <span class="string">&quot;File&quot;</span>
                 id: fileButton
                 <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
                 onButtonClick: menuListView<span class="operator">.</span>currentIndex <span class="operator">=</span> <span class="number">0</span>
             }
             Button{
                 id: editButton
                 label: <span class="string">&quot;Edit&quot;</span>
                 <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
                 onButtonClick:    menuListView<span class="operator">.</span>currentIndex <span class="operator">=</span> <span class="number">1</span>
             }
         }
     }</pre>
<p>The menu bar we just created can be flicked to access the menus or by clicking on the menu names at the top. Switching menu screens feel intuitive and responsive.</p>
<p class="centerAlign"><img src="images/qml-texteditor2_menubar.png" alt="" /></p><a name="building-a-text-editor"></a>
<h2>Building a Text Editor</h2>
<a name="declaring-a-textarea"></a>
<h3>Declaring a TextArea</h3>
<p>Our text editor is not a text editor if it didn't contain an editable text area. QML's <a href="qml-textedit.html">TextEdit</a> element allows the declaration of a multi-line editable text area. <a href="qml-textedit.html">TextEdit</a> is different from a <a href="qml-text.html">Text</a> element, which doesn't allow the user to directly edit the text.</p>
<pre class="cpp">     TextEdit{
         id: textEditor
         anchors<span class="operator">.</span>fill:parent
         width:parent<span class="operator">.</span>width; height:parent<span class="operator">.</span>height
         color:<span class="string">&quot;midnightblue&quot;</span>
         focus: <span class="keyword">true</span>

         wrapMode: TextEdit<span class="operator">.</span>Wrap

         onCursorRectangleChanged: flickArea<span class="operator">.</span>ensureVisible(cursorRectangle)
     }</pre>
<p>The editor has its font color property set and set to wrap the text. The <tt>TextEdit</tt> area is inside a flickable area that will scroll the text if the text cursor is outside the visible area. The function <tt>ensureVisible()</tt> will check if the cursor rectangle is outside the visible boundaries and move the text area accordingly. QML uses Javascript syntax for its scripts, and as previously mentioned, Javascript files can be imported and used within a QML file.</p>
<pre class="cpp">     function ensureVisible(r){
         <span class="keyword">if</span> (contentX <span class="operator">&gt;</span><span class="operator">=</span> r<span class="operator">.</span>x)
             contentX <span class="operator">=</span> r<span class="operator">.</span>x;
         <span class="keyword">else</span> <span class="keyword">if</span> (contentX<span class="operator">+</span>width <span class="operator">&lt;</span><span class="operator">=</span> r<span class="operator">.</span>x<span class="operator">+</span>r<span class="operator">.</span>width)
             contentX <span class="operator">=</span> r<span class="operator">.</span>x<span class="operator">+</span>r<span class="operator">.</span>width<span class="operator">-</span>width;
         <span class="keyword">if</span> (contentY <span class="operator">&gt;</span><span class="operator">=</span> r<span class="operator">.</span>y)
             contentY <span class="operator">=</span> r<span class="operator">.</span>y;
         <span class="keyword">else</span> <span class="keyword">if</span> (contentY<span class="operator">+</span>height <span class="operator">&lt;</span><span class="operator">=</span> r<span class="operator">.</span>y<span class="operator">+</span>r<span class="operator">.</span>height)
             contentY <span class="operator">=</span> r<span class="operator">.</span>y<span class="operator">+</span>r<span class="operator">.</span>height<span class="operator">-</span>height;
     }</pre>
<a name="combining-components-for-the-text-editor"></a>
<h3>Combining Components for the Text Editor</h3>
<p>We are now ready to create the layout of our text editor using QML. The text editor has two components, the menu bar we created and the text area. QML allows us to reuse components, therefore making our code simpler, by importing components and customizing when necessary. Our text editor splits the window into two; one-third of the screen is dedicated to the menu bar and two-thirds of the screen displays the text area. The menu bar is displayed in front of any other elements.</p>
<pre class="cpp">     Rectangle{

         id: screen
         width: <span class="number">1000</span>; height: <span class="number">1000</span>

         <span class="comment">//the screen is partitioned into the MenuBar and TextArea. 1/3 of the screen is assigned to the MenuBar</span>
         property <span class="type">int</span> partition: height<span class="operator">/</span><span class="number">3</span>

         MenuBar{
             id:menuBar
             height: partition
             width:parent<span class="operator">.</span>width
             z: <span class="number">1</span>
         }

         TextArea{
             id:textArea
             anchors<span class="operator">.</span>bottom:parent<span class="operator">.</span>bottom
             y: partition
             color: <span class="string">&quot;white&quot;</span>
             height: partition<span class="operator">*</span><span class="number">2</span>
             width:parent<span class="operator">.</span>width
         }
     }</pre>
<p>By importing reusable components, our <tt>TextEditor</tt> code looks much simpler. We can then customize the main application, without worrying about properties that already have defined behaviors. Using this approach, application layouts and UI components can be created easily.</p>
<p class="centerAlign"><img src="images/qml-texteditor3_texteditor.png" alt="" /></p><a name="decorating-the-text-editor"></a>
<h2>Decorating the Text Editor</h2>
<a name="implementing-a-drawer-interface"></a>
<h3>Implementing a Drawer Interface</h3>
<p>Our text editor looks simple and we need to decorate it. Using QML, we can declare transitions and animate our text editor. Our menu bar is occupying one-third of the screen and it would be nice to have it only appear when we want it.</p>
<p>We can add a drawer interface, that will contract or expand the menu bar when clicked. In our implementation, we have a thin rectangle that responds to mouse clicks. The <tt>drawer</tt>, as well as the application, has two sates: the &quot;drawer is open&quot; state and the &quot;drawer is closed&quot; state. The <tt>drawer</tt> item is a strip of rectangle with a small height. There is a nested <a href="qml-image.html">Image</a> element declaring that an arrow icon will be centered inside the drawer. The drawer assigns a state to the whole application, with the identifier <tt>screen</tt>, whenever a user clicks the mouse area.</p>
<pre class="cpp">     Rectangle{
         id:drawer
         height:<span class="number">15</span>

         Image{
             id: arrowIcon
             source: <span class="string">&quot;images/arrow.png&quot;</span>
             anchors<span class="operator">.</span>horizontalCenter: parent<span class="operator">.</span>horizontalCenter
         }

         MouseArea{
             id: drawerMouseArea
             anchors<span class="operator">.</span>fill:parent
             onClicked:{
                 <span class="keyword">if</span> (screen<span class="operator">.</span>state <span class="operator">=</span><span class="operator">=</span> <span class="string">&quot;DRAWER_CLOSED&quot;</span>){
                     screen<span class="operator">.</span>state <span class="operator">=</span> <span class="string">&quot;DRAWER_OPEN&quot;</span>
                 }
                 <span class="keyword">else</span> <span class="keyword">if</span> (screen<span class="operator">.</span>state <span class="operator">=</span><span class="operator">=</span> <span class="string">&quot;DRAWER_OPEN&quot;</span>){
                     screen<span class="operator">.</span>state <span class="operator">=</span> <span class="string">&quot;DRAWER_CLOSED&quot;</span>
                 }
             }
             <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
         }
     }</pre>
<p>A state is simply a collection of configurations and it is declared in a <a href="qml-state.html">State</a> element. A list of states can be listed and bound to the <tt>states</tt> property. In our application, the two states are called <tt>DRAWER_CLOSED</tt> and <tt>DRAWER_OPEN</tt>. Item configurations are declared in <a href="qml-propertychanges.html">PropertyChanges</a> elements. In the <tt>DRAWER_OPEN</tt> state, there are four items that will receive property changes. The first target, <tt>menuBar</tt>, will change its <tt>y</tt> property to <tt>0</tt>. Similarly, the <tt>textArea</tt> will lower to a new position when the state is <tt>DRAWER_OPEN</tt>. The <tt>textArea</tt>, the <tt>drawer</tt>, and the drawer's icon will undergo property changes to meet the current state.</p>
<pre class="qml">     <span class="name">states</span>:[
         <span class="type"><a href="qml-state.html">State</a></span> {
             <span class="name">name</span>: <span class="string">&quot;DRAWER_OPEN&quot;</span>
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">menuBar</span>; <span class="name">y</span>: <span class="number">0</span>}
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">textArea</span>; <span class="name">y</span>: <span class="name">partition</span> <span class="operator">+</span> <span class="name">drawer</span>.<span class="name">height</span>}
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">drawer</span>; <span class="name">y</span>: <span class="name">partition</span>}
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">arrowIcon</span>; <span class="name">rotation</span>: <span class="number">180</span>}
         },
         <span class="type"><a href="qml-state.html">State</a></span> {
             <span class="name">name</span>: <span class="string">&quot;DRAWER_CLOSED&quot;</span>
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">menuBar</span>; <span class="name">y</span>:-<span class="name">height</span>; }
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">textArea</span>; <span class="name">y</span>: <span class="name">drawer</span>.<span class="name">height</span>; <span class="name">height</span>: <span class="name">screen</span>.<span class="name">height</span> <span class="operator">-</span> <span class="name">drawer</span>.<span class="name">height</span> }
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">drawer</span>; <span class="name">y</span>: <span class="number">0</span> }
             <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">arrowIcon</span>; <span class="name">rotation</span>: <span class="number">0</span> }
         }
     ]</pre>
<p>State changes are abrupt and needs smoother transitions. Transitions between states are defined using the <a href="qml-transition.html">Transition</a> element, which can then bind to the item's <tt>transitions</tt> property. Our text editor has a state transition whenever the state changes to either <tt>DRAWER_OPEN</tt> or <tt>DRAWER_CLOSED</tt>. Importantly, the transition needs a <tt>from</tt> and a <tt>to</tt> state but for our transitions, we can use the wild card <tt>*</tt> symbol to denote that the transition applies to all state changes.</p>
<p>During transitions, we can assign animations to the property changes. Our <tt>menuBar</tt> switches position from <tt>y:0</tt> to <tt>y:-partition</tt> and we can animate this transition using the <a href="qml-numberanimation.html">NumberAnimation</a> element. We declare that the targets' properties will animate for a certain duration of time and using a certain easing curve. An easing curve controls the animation rates and interpolation behavior during state transitions. The easing curve we chose is <a href="qml-propertyanimation.html#easing.type-prop">Easing.OutQuint</a>, which slows the movement near the end of the animation. Please read <a href="qdeclarativeanimation.html">QML's Animation</a> article.</p>
<pre class="qml">     <span class="name">transitions</span>: [
         <span class="type"><a href="qml-transition.html">Transition</a></span> {
             <span class="name">to</span>: <span class="string">&quot;*&quot;</span>
             <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">target</span>: <span class="name">textArea</span>; <span class="name">properties</span>: <span class="string">&quot;y, height&quot;</span>; <span class="name">duration</span>: <span class="number">100</span>; <span class="name">easing</span>.type:<span class="name">Easing</span>.<span class="name">OutExpo</span> }
             <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">target</span>: <span class="name">menuBar</span>; <span class="name">properties</span>: <span class="string">&quot;y&quot;</span>; <span class="name">duration</span>: <span class="number">100</span>; <span class="name">easing</span>.type: <span class="name">Easing</span>.<span class="name">OutExpo</span> }
             <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">target</span>: <span class="name">drawer</span>; <span class="name">properties</span>: <span class="string">&quot;y&quot;</span>; <span class="name">duration</span>: <span class="number">100</span>; <span class="name">easing</span>.type: <span class="name">Easing</span>.<span class="name">OutExpo</span> }
         }
     ]</pre>
<p>Another way of animating property changes is by declaring a <a href="qml-behavior.html">Behavior</a> element. A transition only works during state changes and <tt>Behavior</tt> can set an animation for a general property change. In the text editor, the arrow has a <tt>NumberAnimation</tt> animating its <tt>rotation</tt> property whenever the property changes.</p>
<pre class="cpp"> In TextEditor<span class="operator">.</span>qml:

     Behavior{
         NumberAnimation{property: <span class="string">&quot;rotation&quot;</span>;easing<span class="operator">.</span>type: Easing<span class="operator">.</span>OutExpo }
     }</pre>
<p>Going back to our components with knowledge of states and animations, we can improve the appearances of the components. In <tt>Button.qml</tt>, we can add <tt>color</tt> and <tt>scale</tt> property changes when the button is clicked. Color types are animated using <a href="qml-coloranimation.html">ColorAnimation</a> and numbers are animated using <a href="qml-numberanimation.html">NumberAnimation</a>. The <tt>on propertyName</tt> syntax displayed below is helpful when targeting a single property.</p>
<pre class="cpp"> In Button<span class="operator">.</span>qml:
     <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>

     color: buttonMouseArea<span class="operator">.</span>pressed <span class="operator">?</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">.</span>darker(buttonColor<span class="operator">,</span> <span class="number">1.5</span>) : buttonColor
     Behavior on color { ColorAnimation{ duration: <span class="number">55</span>} }

     scale: buttonMouseArea<span class="operator">.</span>pressed <span class="operator">?</span> <span class="number">1.1</span> : <span class="number">1.00</span>
     Behavior on scale { NumberAnimation{ duration: <span class="number">55</span>} }</pre>
<p>Additionally, we can enhance the appearances of our QML components by adding color effects such as gradients and opacity effects. Declaring a <a href="qml-gradient.html">Gradient</a> element will override the <tt>color</tt> property of the element. You may declare a color in the gradient using the <a href="qml-gradientstop.html">GradientStop</a> element. The gradient is positioned using a scale, between <tt>0.0</tt> and <tt>1.0</tt>.</p>
<pre class="cpp"> In MenuBar<span class="operator">.</span>qml
     gradient: Gradient {
         GradientStop { position: <span class="number">0.0</span>; color: <span class="string">&quot;#8C8F8C&quot;</span> }
         GradientStop { position: <span class="number">0.17</span>; color: <span class="string">&quot;#6A6D6A&quot;</span> }
         GradientStop { position: <span class="number">0.98</span>;color: <span class="string">&quot;#3F3F3F&quot;</span> }
         GradientStop { position: <span class="number">1.0</span>; color: <span class="string">&quot;#0e1B20&quot;</span> }
     }</pre>
<p>This gradient is used by the menu bar to display a gradient simulating depth. The first color starts at <tt>0.0</tt> and the last color is at <tt>1.0</tt>.</p>
<a name="where-to-go-from-here"></a>
<h4>Where to Go from Here</h4>
<p>We are finished building the user interface of a very simple text editor. Going forward, the user interface is complete, and we can implement the application logic using regular Qt and C++. QML works nicely as a prototyping tool, separating the application logic away from the UI design.</p>
<p class="centerAlign"><img src="images/qml-texteditor4_texteditor.png" alt="" /></p><a name="extending-qml-using-qt-c"></a>
<h3>Extending QML using Qt C++</h3>
<p>Now that we have our text editor layout, we may now implement the text editor functionalities in C++. Using QML with C++ enables us to create our application logic using Qt. We can create a QML context in a C++ application using the <a href="qtbinding.html">Qt's Declarative</a> classes and display the QML elements using a Graphics Scene. Alternatively, we can export our C++ code into a plugin that the <a href="qmlviewer.html">qmlviewer</a> tool can read. For our application, we shall implement the load and save functions in C++ and export it as a plugin. This way, we only need to load the QML file directly instead of running an executable.</p>
<a name="exposing-c-classes-to-qml"></a>
<h4>Exposing C++ Classes to QML</h4>
<p>We will be implementing file loading and saving using Qt and C++. C++ classes and functions can be used in QML by registering them. The class also needs to be compiled as a Qt plugin and the QML file will need to know where the plugin is located.</p>
<p>For our application, we need to create the following items:</p>
<ol class="1">
<li><tt>Directory</tt> class that will handle directory related operations</li>
<li><tt>File</tt> class which is a <a href="qobject.html">QObject</a>, simulating the list of files in a directory</li>
<li>plugin class that will register the class to the QML context</li>
<li>Qt project file that will compile the plugin</li>
<li>A <tt>qmldir</tt> file telling the qmlviewer tool where to find the plugin</li>
</ol>
<a name="building-a-qt-plugin"></a>
<h4>Building a Qt Plugin</h4>
<p>To build a plugin, we need to set the following in a Qt project file. First, the necessary sources, headers, and Qt modules need to be added into our project file. All the C++ code and project files are in the <tt>filedialog</tt> directory.</p>
<pre class="cpp"> In filedialog<span class="operator">.</span>pro:

     TEMPLATE <span class="operator">=</span> lib
     CONFIG <span class="operator">+</span><span class="operator">=</span> qt plugin
     QT <span class="operator">+</span><span class="operator">=</span> declarative

     DESTDIR <span class="operator">+</span><span class="operator">=</span>  <span class="operator">.</span><span class="operator">.</span><span class="operator">/</span>plugins
     OBJECTS_DIR <span class="operator">=</span> tmp
     MOC_DIR <span class="operator">=</span> tmp

     TARGET <span class="operator">=</span> FileDialog

     HEADERS <span class="operator">+</span><span class="operator">=</span>     directory<span class="operator">.</span>h \
             file<span class="operator">.</span>h \
             dialogPlugin<span class="operator">.</span>h

     SOURCES <span class="operator">+</span><span class="operator">=</span>    directory<span class="operator">.</span>cpp \
             file<span class="operator">.</span>cpp \
             dialogPlugin<span class="operator">.</span>cpp</pre>
<p>In particular, we compile Qt with the <tt>declarative</tt> module and configure it as a <tt>plugin</tt>, needing a <tt>lib</tt> template. We shall put the compiled plugin into the parent's <tt>plugins</tt> directory.</p>
<a name="registering-a-class-into-qml"></a>
<h4>Registering a Class into QML</h4>
<pre class="cpp"> In dialogPlugin<span class="operator">.</span>h:

     <span class="preprocessor">#include &lt;QtDeclarative/QDeclarativeExtensionPlugin&gt;</span>

     <span class="keyword">class</span> DialogPlugin : <span class="keyword">public</span> <span class="type"><a href="qdeclarativeextensionplugin.html">QDeclarativeExtensionPlugin</a></span>
     {
         Q_OBJECT

         <span class="keyword">public</span>:
         <span class="type">void</span> registerTypes(<span class="keyword">const</span> <span class="type">char</span> <span class="operator">*</span>uri);

     };</pre>
<p>Our plugin class, <tt>DialogPlugin</tt> is a subclass of <a href="qdeclarativeextensionplugin.html">QDeclarativeExtensionPlugin</a>. We need to implement the inherited function, <a href="qdeclarativeextensionplugin.html#registerTypes">registerTypes()</a>. The <tt>dialogPlugin.cpp</tt> file looks like this:</p>
<pre class="cpp"> DialogPlugin<span class="operator">.</span>cpp:

     <span class="preprocessor">#include &quot;dialogPlugin.h&quot;</span>
     <span class="preprocessor">#include &quot;directory.h&quot;</span>
     <span class="preprocessor">#include &quot;file.h&quot;</span>
     <span class="preprocessor">#include &lt;QtDeclarative/qdeclarative.h&gt;</span>

     <span class="type">void</span> DialogPlugin<span class="operator">::</span>registerTypes(<span class="keyword">const</span> <span class="type">char</span> <span class="operator">*</span>uri){

         qmlRegisterType<span class="operator">&lt;</span>Directory<span class="operator">&gt;</span>(uri<span class="operator">,</span> <span class="number">1</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="string">&quot;Directory&quot;</span>);
         qmlRegisterType<span class="operator">&lt;</span>File<span class="operator">&gt;</span>(uri<span class="operator">,</span> <span class="number">1</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span><span class="string">&quot;File&quot;</span>);
     }

     <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>(FileDialog<span class="operator">,</span> DialogPlugin);</pre>
<p>The <a href="qdeclarativeextensionplugin.html#registerTypes">registerTypes()</a> function registers our File and Directory classes into QML. This function needs the class name for its template, a major version number, a minor version number, and a name for our classes.</p>
<p>We need to export the plugin using the <a href="qtplugin.html#Q_EXPORT_PLUGIN2#q-export-plugin2">Q_EXPORT_PLUGIN2</a> macro. Note that in our <tt>dialogPlugin.h</tt> file, we have the <a href="qobject.html#Q_OBJECT">Q_OBJECT</a> macro at the top of our class. As well, we need to run <tt>qmake</tt> on the project file to generate the necessary meta-object code.</p>
<a name="creating-qml-properties-in-a-c-class"></a>
<h4>Creating QML Properties in a C++ class</h4>
<p>We can create QML elements and properties using C++ and <a href="metaobjects.html">Qt's Meta-Object System</a>. We can implement properties using slots and signals, making Qt aware of these properties. These properties can then be used in QML.</p>
<p>For the text editor, we need to be able to load and save files. Typically, these features are contained in a file dialog. Fortunately, we can use <a href="qdir.html">QDir</a>, <a href="qfile.html">QFile</a>, and <a href="qtextstream.html">QTextStream</a> to implement directory reading and input/output streams.</p>
<pre class="cpp">     <span class="keyword">class</span> Directory : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span>{

         Q_OBJECT

         Q_PROPERTY(<span class="type">int</span> filesCount READ filesCount CONSTANT)
         Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> filename READ filename WRITE setFilename NOTIFY filenameChanged)
         Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> fileContent READ fileContent WRITE setFileContent NOTIFY fileContentChanged)
         Q_PROPERTY(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> files READ files CONSTANT )

         <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span></pre>
<p>The <tt>Directory</tt> class uses Qt's Meta-Object System to register properties it needs to accomplish file handling. The <tt>Directory</tt> class is exported as a plugin and is useable in QML as the <tt>Directory</tt> element. Each of the listed properties using the <a href="qobject.html#Q_PROPERTY">Q_PROPERTY</a> macro is a QML property.</p>
<p>The <a href="qobject.html#Q_PROPERTY">Q_PROPERTY</a> declares a property as well as its read and write functions into Qt's Meta-Object System. For example, the <tt>filename</tt> property, of type <a href="qstring.html">QString</a>, is readable using the <tt>filename()</tt> function and writable using the function <tt>setFilename()</tt>. Additionally, there is a signal associated to the filename property called <tt>filenameChanged()</tt>, which is emitted whenever the property changes. The read and write functions are declared as <tt>public</tt> in the header file.</p>
<p>Similarly, we have the other properties declared according to their uses. The <tt>filesCount</tt> property indicates the number of files in a directory. The filename property is set to the currently selected file's name and the loaded/saved file content is stored in <tt>fileContent</tt> property.</p>
<pre class="cpp">     <a href="qobject.html#Q_PROPERTY">Q_PROPERTY</a>(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> files READ files CONSTANT )</pre>
<p>The <tt>files</tt> list property is a list of all the filtered files in a directory. The <tt>Directory</tt> class is implemented to filter out invalid text files; only files with a <tt>.txt</tt> extension are valid. Further, <a href="qlist.html">QList</a>s can be used in QML files by declaring them as a <a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a> in C++. The templated object needs to inherit from a <a href="qobject.html">QObject</a>, therefore, the <tt>File</tt> class must also inherit from <a href="qobject.html">QObject</a>. In the <tt>Directory</tt> class, the list of <tt>File</tt> objects is stored in a <a href="qlist.html">QList</a> called <tt>m_fileList</tt>.</p>
<pre class="cpp">     <span class="keyword">class</span> File : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span>{

         Q_OBJECT
         Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> name READ name WRITE setName NOTIFY nameChanged)

         <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>
     };</pre>
<p>The properties can then be used in QML as part of the <tt>Directory</tt> element's properties. Note that we do not have to create an identifier <tt>id</tt> property in our C++ code.</p>
<pre class="cpp">     Directory{
         id: directory

         filesCount
         filename
         fileContent
         files

         files<span class="operator">[</span><span class="number">0</span><span class="operator">]</span><span class="operator">.</span>name
     }</pre>
<p>Because QML uses Javascript's syntax and structure, we can iterate through the list of files and retrieve its properties. To retrieve the first file's name property, we can call <tt>files[0].name</tt>.</p>
<p>Regular C++ functions are also accessible from QML. The file loading and saving functions are implemented in C++ and declared using the <a href="qobject.html#Q_INVOKABLE">Q_INVOKABLE</a> macro. Alternatively, we can declare the functions as a <tt>slot</tt> and the functions will be accessible from QML.</p>
<pre class="cpp"> In Directory<span class="operator">.</span>h:

     Q_INVOKABLE <span class="type">void</span> saveFile();
     Q_INVOKABLE <span class="type">void</span> loadFile();</pre>
<p>The <tt>Directory</tt> class also has to notify other objects whenever the directory contents change. This feature is performed using a <tt>signal</tt>. As previously mentioned, QML signals have a corresponding handler with their names prepended with <tt>on</tt>. The signal is called <tt>directoryChanged</tt> and it is emitted whenever there is a directory refresh. The refresh simply reloads the directory contents and updates the list of valid files in the directory. QML items can then be notified by attaching an action to the <tt>onDirectoryChanged</tt> signal handler.</p>
<p>The <tt>list</tt> properties need to be explored further. This is because list properties use callbacks to access and modify the list contents. The list property is of type <tt>QDeclarativeListProperty&lt;File&gt;</tt>. Whenever the list is accessed, the accessor function needs to return a <tt>QDeclarativeListProperty&lt;File&gt;</tt>. The template type, <tt>File</tt>, needs to be a <tt>QObject</tt> derivative. Further, to create the <a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a>, the list's accessor and modifiers need to be passed to the constructor as function pointers. The list, a <tt>QList</tt> in our case, also needs to be a list of <tt>File</tt> pointers.</p>
<p>The constructor of <a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a> constructor and the <tt>Directory</tt> implementation:</p>
<pre class="cpp">     <span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span>  ( <span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span> object<span class="operator">,</span> <span class="type">void</span> <span class="operator">*</span> data<span class="operator">,</span> AppendFunction append<span class="operator">,</span> CountFunction count <span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> AtFunction at <span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> ClearFunction clear <span class="operator">=</span> <span class="number">0</span> )
     <span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span>( <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>m_fileList<span class="operator">,</span> <span class="operator">&amp;</span>appendFiles<span class="operator">,</span> <span class="operator">&amp;</span>filesSize<span class="operator">,</span> <span class="operator">&amp;</span>fileAt<span class="operator">,</span>  <span class="operator">&amp;</span>clearFilesPtr );</pre>
<p>The constructor passes pointers to functions that will append the list, count the list, retrieve the item using an index, and empty the list. Only the append function is mandatory. Note that the function pointers must match the definition of <a href="qdeclarativelistproperty.html#AppendFunction-typedef">AppendFunction</a>, <a href="qdeclarativelistproperty.html#CountFunction-typedef">CountFunction</a>, <a href="qdeclarativelistproperty.html#AtFunction-typedef">AtFunction</a>, or <a href="qdeclarativelistproperty.html#ClearFunction-typedef">ClearFunction</a>.</p>
<pre class="cpp">     <span class="type">void</span> appendFiles(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> <span class="operator">*</span> property<span class="operator">,</span> File <span class="operator">*</span> file)
     File<span class="operator">*</span> fileAt(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> <span class="operator">*</span> property<span class="operator">,</span> <span class="type">int</span> index)
     <span class="type">int</span> filesSize(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> <span class="operator">*</span> property)
     <span class="type">void</span> clearFilesPtr(<span class="type"><a href="qdeclarativelistproperty.html">QDeclarativeListProperty</a></span><span class="operator">&lt;</span>File<span class="operator">&gt;</span> <span class="operator">*</span>property)</pre>
<p>To simplify our file dialog, the <tt>Directory</tt> class filters out invalid text files, which are files that do not have a <tt>.txt</tt> extension. If a file name doesn't have the <tt>.txt</tt> extension, then it won't be seen in our file dialog. Also, the implementation makes sure that saved files have a <tt>.txt</tt> extension in the file name. <tt>Directory</tt> uses <a href="qtextstream.html">QTextStream</a> to read the file and to output the file contents to a file.</p>
<p>With our <tt>Directory</tt> element, we can retrieve the files as a list, know how many text files is in the application directory, get the file's name and content as a string, and be notified whenever there are changes in the directory contents.</p>
<p>To build the plugin, run <tt>qmake</tt> on the <tt>filedialog.pro</tt> project file, then run <tt>make</tt> to build and transfer the plugin to the <tt>plugins</tt> directory.</p>
<a name="importing-a-plugin-in-qml"></a>
<h4>Importing a Plugin in QML</h4>
<p>The qmlviewer tool imports files that are in the same directory as the application. We can also create a <tt>qmldir</tt> file containing the locations of QML files we wish to import. The <tt>qmldir</tt> file can also store locations of plugins and other resources.</p>
<pre class="cpp"> In qmldir:

     Button <span class="operator">.</span><span class="operator">/</span>Button<span class="operator">.</span>qml
     FileDialog <span class="operator">.</span><span class="operator">/</span>FileDialog<span class="operator">.</span>qml
     TextArea <span class="operator">.</span><span class="operator">/</span>TextArea<span class="operator">.</span>qml
     TextEditor <span class="operator">.</span><span class="operator">/</span>TextEditor<span class="operator">.</span>qml
     EditMenu <span class="operator">.</span><span class="operator">/</span>EditMenu<span class="operator">.</span>qml

     plugin FileDialog plugins</pre>
<p>The plugin we just created is called <tt>FileDialog</tt>, as indicated by the <tt>TARGET</tt> field in the project file. The compiled plugin is in the <tt>plugins</tt> directory.</p>
<a name="integrating-a-file-dialog-into-the-file-menu"></a>
<h4>Integrating a File Dialog into the File Menu</h4>
<p>Our <tt>FileMenu</tt> needs to display the <tt>FileDialog</tt> element, containing a list of the text files in a directory thus allowing the user to select the file by clicking on the list. We also need to assign the save, load, and new buttons to their respective actions. The FileMenu contains an editable text input to allow the user to type a file name using the keyboard.</p>
<p>The <tt>Directory</tt> element is used in the <tt>FileMenu.qml</tt> file and it notifies the <tt>FileDialog</tt> element that the directory refreshed its contents. This notification is performed in the signal handler, <tt>onDirectoryChanged</tt>.</p>
<pre class="cpp"> In FileMenu<span class="operator">.</span>qml:

     Directory{
         id:directory
         filename: textInput<span class="operator">.</span>text
         onDirectoryChanged: fileDialog<span class="operator">.</span>notifyRefresh()
     }</pre>
<p>Keeping with the simplicity of our application, the file dialog will always be visible and will not display invalid text files, which do not have a <tt>.txt</tt> extension to their filenames.</p>
<pre class="cpp"> In FileDialog<span class="operator">.</span>qml:

     signal notifyRefresh()
     onNotifyRefresh: dirView<span class="operator">.</span>model <span class="operator">=</span> directory<span class="operator">.</span>files</pre>
<p>The <tt>FileDialog</tt> element will display the contents of a directory by reading its list property called <tt>files</tt>. The files are used as the model of a <a href="qml-gridview.html">GridView</a> element, which displays data items in a grid according to a delegate. The delegate handles the appearance of the model and our file dialog will simply create a grid with text centered in the middle. Clicking on the file name will result in the appearance of a rectangle to highlight the file name. The <tt>FileDialog</tt> is notified whenever the <tt>notifyRefresh</tt> signal is emitted, reloading the files in the directory.</p>
<pre class="cpp"> In FileMenu<span class="operator">.</span>qml:

     Button{
         id: newButton
         label: <span class="string">&quot;New&quot;</span>
         onButtonClick:{
             textArea<span class="operator">.</span>textContent <span class="operator">=</span> <span class="string">&quot;&quot;</span>
         }
     }
     Button{
         id: loadButton
         label: <span class="string">&quot;Load&quot;</span>
         onButtonClick:{
             directory<span class="operator">.</span>filename <span class="operator">=</span> textInput<span class="operator">.</span>text
             directory<span class="operator">.</span>loadFile()
             textArea<span class="operator">.</span>textContent <span class="operator">=</span> directory<span class="operator">.</span>fileContent
         }
     }
     Button{
         id: saveButton
         label: <span class="string">&quot;Save&quot;</span>
         onButtonClick:{
             directory<span class="operator">.</span>fileContent <span class="operator">=</span> textArea<span class="operator">.</span>textContent
             directory<span class="operator">.</span>filename <span class="operator">=</span> textInput<span class="operator">.</span>text
             directory<span class="operator">.</span>saveFile()
         }
     }
     Button{
         id: exitButton
         label: <span class="string">&quot;Exit&quot;</span>
         onButtonClick:{
             <span class="type"><a href="qt.html">Qt</a></span><span class="operator">.</span>quit()
         }
     }</pre>
<p>Our <tt>FileMenu</tt> can now connect to their respective actions. The <tt>saveButton</tt> will transfer the text from the <tt>TextEdit</tt> onto the directory's <tt>fileContent</tt> property, then copy its file name from the editable text input. Finally, the button calls the <tt>saveFile()</tt> function, saving the file. The <tt>loadButton</tt> has a similar execution. Also, the <tt>New</tt> action will empty the contents of the <tt>TextEdit</tt>.</p>
<p>Further, the <tt>EditMenu</tt> buttons are connected to the <tt>TextEdit</tt> functions to copy, paste, and select all the text in the text editor.</p>
<p class="centerAlign"><img src="images/qml-texteditor5_filemenu.png" alt="" /></p><a name="text-editor-completion"></a>
<h3>Text Editor Completion</h3>
<p class="centerAlign"><img src="images/qml-texteditor5_newfile.png" alt="" /></p><p>The application can function as a simple text editor, able to accept text and save the text into a file. The text editor can also load from a file and perform text manipulation.</p>
<a name="running-the-text-editor"></a>
<h2>Running the Text Editor</h2>
<p>We need to compile the file dialog C++ plugin before the text editor can run. To compile, enter the <tt>gsQml</tt> directory, then run <tt>qmake</tt> and compile using <tt>make</tt> or <tt>nmake</tt>, depending on your platform. To run, launch qmlviewer and open the <tt>texteditor.qml</tt> file.</p>
<p>The source code is in the <tt>examples/tutorials/gettingStarted/gsQml</tt> directory.</p>
</div>
<!-- @@@gettingstartedqml.html -->
      </div>
    </div>
    </div> 
    <div class="ft">
      <span></span>
    </div>
  </div> 
  <div class="footer">
    <p>
      <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.</p>
    <br />
    <p>
      The documentation provided herein is licensed under the terms of the
      <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
      License version 1.3</a> as published by the Free Software Foundation.</p>
    <p>
      Documentation sources may be obtained from <a href="http://www.qt-project.org">
      www.qt-project.org</a>.</p>
    <br />
    <p>
      Digia, Qt and their respective logos are trademarks of Digia Plc 
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. <a title="Privacy Policy"
      href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
  </div>

  <script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>