Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

QML Scope

QML property bindings, inline functions and imported JavaScript files all run in a JavaScript scope. Scope controls which variables an expression can access, and which variable takes precedence when two or more names conflict.

As JavaScript's built-in scope mechanism is very simple, QML enhances it to fit more naturally with the QML language extensions.

JavaScript Scope

QML's scope extensions do not interfere with JavaScript's natural scoping. JavaScript programmers can reuse their existing knowledge when programming functions, property bindings or imported JavaScript files in QML.

In the following example, the addConstant() method will add 13 to the parameter passed just as the programmer would expect irrespective of the value of the QML object's a and b properties.

 QtObject {
     property int a: 3
     property int b: 9

     function addConstant(b) {
         var a = 13;
         return b + a;
     }
 }

That QML respects JavaScript's normal scoping rules even applies in bindings. This totally evil, abomination of a binding will assign 12 to the QML object's a property.

 QtObject {
     property int a

     a: { var a = 12; a; }
 }

Every JavaScript expression, function or file in QML has its own unique variable object. Local variables declared in one will never conflict with local variables declared in another.

Element Names and Imported JavaScript Files

QML Documents include import statements that define the element names and JavaScript files visible to the document. In addition to their use in the QML declaration itself, element names are used by JavaScript code when accessing Attached Properties and enumeration values.

The effect of an import applies to every property binding, and JavaScript function in the QML document, even those in nested inline components. The following example shows a simple QML file that accesses some enumeration values and calls an imported JavaScript function.

 import QtQuick 1.0
 import "code.js" as Code

 ListView {
     snapMode: ListView.SnapToItem

     delegate: Component {
         Text {
             elide: Text.ElideMiddle
             text: "A really, really long string that will require eliding."
             color: Code.defaultColor()
         }
     }
 }

Binding Scope Object

Property bindings are the most common use of JavaScript in QML. Property bindings associate the result of a JavaScript expression with a property of an object. The object to which the bound property belongs is known as the binding's scope object. In this QML simple declaration the Item object is the binding's scope object.

 Item {
     anchors.left: parent.left
 }

Bindings have access to the scope object's properties without qualification. In the previous example, the binding accesses the Item's parent property directly, without needing any form of object prefix. QML introduces a more structured, object-oriented approach to JavaScript, and consequently does not require the use of the JavaScript this property.

Care must be used when accessing Attached Properties from bindings due to their interaction with the scope object. Conceptually attached properties exist on all objects, even if they only have an effect on a subset of those. Consequently unqualified attached property reads will always resolve to an attached property on the scope object, which is not always what the programmer intended.

For example, the PathView element attaches interpolated value properties to its delegates depending on their position in the path. As PathView only meaningfully attaches these properties to the root element in the delegate, any sub-element that accesses them must explicitly qualify the root object, as shown below.

 PathView {
     delegate: Component {
         Rectangle {
             id: root
             Image {
                 scale: root.PathView.scale
             }
         }
     }
 }

If the Image element omitted the root prefix, it would inadvertently access the unset PathView.scale attached property on itself.

Component Scope

Each QML component in a QML document defines a logical scope. Each document has at least one root component, but can also have other inline sub-components. The component scope is the union of the object ids within the component and the component's root element's properties.

 Item {
     property string title

     Text {
         id: titleElement
         text: "<b>" + title + "</b>"
         font.pixelSize: 22
         anchors.top: parent.top
     }

     Text {
         text: titleElement.text
         font.pixelSize: 18
         anchors.bottom: parent.bottom
     }
 }

The example above shows a simple QML component that displays a rich text title string at the top, and a smaller copy of the same text at the bottom. The first Text element directly accesses the component's title property when forming the text to display. That the root element's properties are directly accessible makes it trivial to distribute data throughout the component.

The second Text element uses an id to access the first's text directly. IDs are specified explicitly by the QML programmer so they always take precedence over other property names (except for those in the JavaScript Scope). For example, in the unlikely event that the binding's scope object had a titleElement property in the previous example, the titleElement id would still take precedence.

Component Instance Hierarchy

In QML, component instances connect their component scopes together to form a scope hierarchy. Component instances can directly access the component scopes of their ancestors.

The easiest way to demonstrate this is with inline sub-components whose component scopes are implicitly scoped as children of the outer component.

 Item {
     property color defaultColor: "blue"

     ListView {
         delegate: Component {
             Rectangle {
                 color: defaultColor
             }
         }
     }
 }

The component instance hierarchy allows instances of the delegate component to access the defaultColor property of the Item element. Of course, had the delegate component had a property called defaultColor that would have taken precedence.

The component instance scope hierarchy extends to out-of-line components, too. In the following example, the TitlePage.qml component creates two TitleText instances. Even though the TitleText element is in a separate file, it still has access to the title property when it is used from within the TitlePage. QML is a dynamically scoped language - depending on where it is used, the title property may resolve differently.

 // TitlePage.qml
 import QtQuick 1.0
 Item {
     property string title

     TitleText {
         size: 22
         anchors.top: parent.top
     }

     TitleText {
         size: 18
         anchors.bottom: parent.bottom
     }
 }

 // TitleText.qml
 import QtQuick 1.0
 Text {
     property int size
     text: "<b>" + title + "</b>"
     font.pixelSize: size
 }

Dynamic scoping is very powerful, but it must be used cautiously to prevent the behavior of QML code from becoming difficult to predict. In general it should only be used in cases where the two components are already tightly coupled in another way. When building reusable components, it is preferable to use property interfaces, like this:

 // TitlePage.qml
 import QtQuick 1.0
 Item {
     id: root
     property string title

     TitleText {
         title: root.title
         size: 22
         anchors.top: parent.top
     }

     TitleText {
         title: root.title
         size: 18
         anchors.bottom: parent.bottom
     }
 }

 // TitleText.qml
 import QtQuick 1.0
 Text {
     property string title
     property int size

     text: "<b>" + title + "</b>"
     font.pixelSize: size
 }

JavaScript Global Object

In addition to all the properties that a developer would normally expect on the JavaScript global object, QML adds some custom extensions to make UI or QML specific tasks a little easier. These extensions are described in the QML Global Object documentation.

QML disallows element, id and property names that conflict with the properties on the global object to prevent any confusion. Programmers can be confident that Math.min(10, 9) will always work as expected!

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 56
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 97
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 32
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 231
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  7. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
Page suivante

Le Qt Developer Network au hasard

Logo

Applications mobiles modernes avec Qt et QML

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web