QML

QML
ParadigmMulti-paradigm: declarative, reactive, scripting
DeveloperQt Project
First appeared2009; 16 years ago (2009)
Stable release
6.4[1] / September 29, 2022; 2 years ago (2022-09-29)
Typing disciplinedynamic, strong
Websitedoc.qt.io/qt-5/qmlapplications.html
Influenced by
XAML,[2] JSON, JavaScript, Qt
Influenced
Qt, Ring[3]
QML
Filename extension
.qml
Internet media typetext/x-qml
Developed byQt Project
Type of formatScripting language
Websiteqt-project.org/doc/qt-5/qmlapplications.html

QML (Qt Modeling Language[4]) is a user interface markup language. It is a declarative language (similar to CSS and JSON) for designing user interface–centric applications. Inline JavaScript code handles imperative aspects. It is associated with Qt Quick, the UI creation kit originally developed by Nokia within the Qt framework. Qt Quick is used for mobile applications where touch input, fluid animations and user experience are crucial. QML is also used with Qt3D[5] to describe a 3D scene and a "frame graph" rendering methodology. A QML document describes a hierarchical object tree. QML modules[6] shipped with Qt include primitive graphical building blocks (e.g., Rectangle, Image), modeling components (e.g., FolderListModel, XmlListModel), behavioral components (e.g., TapHandler, DragHandler, State, Transition, Animation), and more complex controls (e.g., Button, Slider, Drawer, Menu). These elements can be combined to build components ranging in complexity from simple buttons and sliders, to complete internet-enabled programs.

QML elements can be augmented by standard JavaScript both inline and via included .js files. Elements can also be seamlessly integrated and extended by C++ components using the Qt framework.

QML is the language; its JavaScript runtime is the custom V4 engine,[7] since Qt 5.2;[8] and Qt Quick is the 2D scene graph and the UI framework based on it. These are all part of the Qt Declarative module, while the technology is no longer called Qt Declarative.

QML and JavaScript code can be compiled into native C++ binaries with the Qt Quick Compiler.[9] Alternatively there is a QML cache file format[10] which stores a compiled version of QML dynamically for faster startup the next time it is run.

Adoption

Syntax, semantics

Basic syntax

Example:

 import QtQuick

 Rectangle {
     id: canvas
     width: 250
     height: 200
     color: "blue"

     Image {
         id: logo
         source: "pics/logo.png"
         anchors.centerIn: parent
         x: canvas.height / 5
     }
 }

Objects are specified by their type, followed by a pair of braces. Object types always begin with a capital letter. In the example above, there are two objects, a Rectangle; and its child, an Image. Between the braces, one can specify information about the object, such as its properties. Properties are specified as property: value. In the example above, we can see the Image has a property named source, which has been assigned the value pics/logo.png. The property and its value are separated by a colon.

The id property

Each object can be given a special unique property called an id. Assigning an id enables the object to be referred to by other objects and scripts. The first Rectangle element below has an id, myRect. The second Rectangle element defines its own width by referring to myRect.width, which means it will have the same width value as the first Rectangle element.

 Item {
     Rectangle {
         id: myRect
         width: 120
         height: 100
     }
     Rectangle {
         width: myRect.width
         height: 200
     }
 }

Note that an id must begin with a lower-case letter or an underscore, and cannot contain characters other than letters, digits and underscores.

Property bindings

A property binding specifies the value of a property in a declarative way. The property value is automatically updated if the other properties or data values change, following the reactive programming paradigm.

Property bindings are created implicitly in QML whenever a property is assigned a JavaScript expression. The following QML uses two property bindings to connect the size of the rectangle to that of otherItem.

 Rectangle {
     width: otherItem.width
     height: otherItem.height
 }

QML extends a standards-compliant JavaScript engine, so any valid JavaScript expression can be used as a property binding. Bindings can access object properties, make function calls, and even use built-in JavaScript objects like Date and Math.

Example:

 Rectangle {
     function calculateMyHeight() {
         return Math.max(otherItem.height, thirdItem.height);
     }
     anchors.centerIn: parent
     width: Math.min(otherItem.width, 10)
     height: calculateMyHeight()
     color: width > 10 ? "blue" : "red"
 }

States

States are a mechanism to combine changes to properties in a semantic unit. A button for example has a pressed and a non-pressed state, an address book application could have a read-only and an edit state for contacts. Every element has an "implicit" base state. Every other state is described by listing the properties and values of those elements which differ from the base state.

Example: In the default state, myRect is positioned at 0,0. In the "moved" state, it is positioned at 50,50. Clicking within the mouse area changes the state from the default state to the "moved" state, thus moving the rectangle.

 import QtQuick

 Item {
     id: myItem
     width: 200; height: 200

     Rectangle {
         id: myRect
         width: 100; height: 100
         color: "red"
     }
     states: [
         State {
             name: "moved"
             PropertyChanges {
                 target: myRect
                 x: 50
                 y: 50
             }
         }
     ]
     MouseArea {
         anchors.fill: parent
         onClicked: myItem.state = 'moved'
     }
 }

State changes can be animated using Transitions.

For example, adding this code to the above Item element animates the transition to the "moved" state:

 transitions: [
     Transition {
         from: "*"
         to: "moved"
         NumberAnimation { properties: "x,y"; duration: 500 }
     }
  ]

Animation

Animations in QML are done by animating properties of objects. Properties of type real, int, color, rect, point, size, and vector3d can all be animated.

QML supports three main forms of animation: basic property animation, transitions, and property behaviors.

The simplest form of animation is a PropertyAnimation, which can animate all of the property types listed above. A property animation can be specified as a value source using the Animation on property syntax. This is especially useful for repeating animations.

The following example creates a bouncing effect:

 Rectangle {
     id: rect
     width: 120; height: 200

     Image {
         id: img
         source: "pics/qt.png"
         x: 60 - img.width/2
         y: 0

         SequentialAnimation on y {
             loops: Animation.Infinite
             NumberAnimation { to: 200 - img.height; easing.type: Easing.OutBounce; duration: 2000 }
             PauseAnimation { duration: 1000 }
             NumberAnimation { to: 0; easing.type: Easing.OutQuad; duration: 1000 }
         }
     }
 }

Qt/C++ integration

Usage of QML does not require Qt/C++ knowledge to use, but it can be easily extended via Qt.[28][29] Any C++ class derived from QObject can be easily registered as a type which can then be instantiated in QML.

Familiar concepts

QML provides direct access to the following concepts from Qt:

  • QObject signals – can trigger callbacks in JavaScript
  • QObject slots – available as functions to call in JavaScript
  • QObject properties – available as variables in JavaScript, and for bindings
  • QWindow – Window creates a QML scene in a window
  • Q*Model – used directly in data binding (e.g. QAbstractItemModel)[30][31][32]

Signal handlers

Signal handlers are JavaScript callbacks which allow imperative actions to be taken in response to an event. For instance, the MouseArea element has signal handlers to handle mouse press, release and click:

 MouseArea {
     onPressed: console.log("mouse button pressed")
 }

All signal handler names begin with "on".

Development tools

Because QML and JavaScript are very similar, almost all code editors supporting JavaScript will work. However full support for syntax highlighting, code completion, integrated help, and a WYSIWYG editor are available in the free cross-platform IDE Qt Creator since version 2.1 and many other IDEs.

The qml executable can be used to run a QML file as a script. If the QML file begins with a shebang it can be made directly executable. However packaging an application for deployment (especially on mobile platforms) generally involves writing a simple C++ launcher and packaging the necessary QML files as resources.

References

  1. ^ "Qt 6.4 Released".
  2. ^ "Which interface for a modern application?". scriptol.
  3. ^ Ring Team (5 December 2017). "The Ring programming language and other languages". ring-lang.net. ring-lang. Archived from the original on 25 December 2018. Retrieved 5 December 2017.
  4. ^ "Qt Declarative API Changes | Qt Blog". March 25, 2014. Archived from the original on March 25, 2014.
  5. ^ "Qt 3D Overview | Qt 3D 5.13.1". doc.qt.io.
  6. ^ "All QML Types | Qt 5.13". doc.qt.io. Retrieved September 7, 2019.
  7. ^ Knoll, Lars (2013-04-15). "Evolution of the QML engine, part 1". Retrieved 2018-05-11.
  8. ^ "What's New in Qt 5.2". Retrieved 2018-05-11.
  9. ^ "Qt Quick Compiler". Retrieved September 7, 2019.
  10. ^ "Deploying QML Applications | Qt 5.13". doc.qt.io. Retrieved September 7, 2019.
  11. ^ "Development/Tutorials/Plasma4/QML/GettingStarted". KDE TechBase. KDE.
  12. ^ Dragly, Svenn-Arne (December 2017). "Developing for the reMarkable tablet". dragly.
  13. ^ "QML Demo for the reMarkable Paper Tablet". GitHub. 9 March 2022.
  14. ^ "Ubuntu's Unity Written In Qt/QML For "Unity Next"". Michael Larabel.
  15. ^ "Combining C++ with QML in Sailfish OS applications".
  16. ^ "Tutorial - QML Live Coding With Qt QmlLive".
  17. ^ "QML to C++ and C++ to QML". Jolla.
  18. ^ "QML fundamentals". Blackberry.
  19. ^ "Intro to QML for Meego". Nokia. Archived from the original on 2018-01-04. Retrieved 2018-01-03.
  20. ^ "MeeGo and Qt / QML demos assault MWC". IoT Gadgets. 23 February 2011.
  21. ^ "QML on N900". maemo.org. Maemo Community.
  22. ^ "Qt Launches on Tizen with Standard Look and Feel". 20 May 2013.
  23. ^ "Mer".
  24. ^ "Mer wiki".
  25. ^ "Lipstick QML UI on MeeGo CE / Mer". IoT Gadgets. 6 October 2011.
  26. ^ "QML - the best tool to unlock your creativity". Ubuntu.
  27. ^ "Looking at Lumina Desktop 2.0". TrueOS. 19 August 2020.
  28. ^ Alpert, Alan. "The Qt/QML User Story". Incorrigible Imaginings.
  29. ^ Alpert, Alan. "The many ways to unite QML and C++". Qt Developer Days. BlackBerry.
  30. ^ Dahlbom, J (22 April 2010). "QAbstractItemModels in QML views". The missing pieces.
  31. ^ "Sorting and filtering a TableView". The Qt Company.
  32. ^ Brad, van der Laan (11 July 2014). "How to use Qt's QSortFilterProxyModel". ImaginativeThinking.

How-tos

Read other articles:

Israeli rapper The ShadowEliasi in 2009Background informationBirth nameYoav EliasiBorn (1977-11-22) November 22, 1977 (age 46)OriginSafed, IsraelGenres Hip hop Israeli hip hop political hip hop Years active1994–presentLabelsUnicellMusical artist Yoav Eliasi (Hebrew: יואב אליאסי; born November 22, 1977), commonly known by his stage name The Shadow (Hebrew: הצל, Ha-Tzel) is an Israeli rapper, blogger, and right-wing political activist. He was part of the roster of artists on...

 

 

Stream in the U.S. state of Connecticut Duck Riverby Jerry Weiss, 2004 The Duck River is a short, partly tidal stream in Old Lyme, Connecticut. It joins the Connecticut River in the estuary at Watch Rock Park, just above the point where the Connecticut flows into Long Island Sound.[1][2][3] The river bisects the Old Lyme Cemetery. The Duck River is popular among artists and photographers. See also List of rivers of Connecticut References ^ CWTA - New London County Wate...

 

 

David O. RussellDavid O. Russell pada acara perdana film American Hustle di Paris bulan Februari 2014LahirDavid Owen Russell20 Agustus 1958 (umur 65)Manhattan, kota New York, New York, Amerika SerikatTempat tinggalSanta Monica, California, Amerika SerikatNama lainDavid O'RussellStephen GreeneAlmamaterAmherst College (B.A.)PekerjaanSutradara, penulis naskah, produserTahun aktif1987–sekarangSuami/istriJanet Grillo ​(m. 1992⁠–⁠2007)...

Mestaruussarja 1981 Competizione Mestaruussarja Sport Calcio Edizione 72ª Organizzatore SPL/FBF Luogo  Finlandia Partecipanti 12 Formula doppia fase Risultati Vincitore HJK(13º titolo) Secondo KPT Kuopio Retrocessioni RoPSMPMiPK Statistiche Miglior marcatore Juhani Himanka (22) Incontri disputati 276 Gol segnati 914 (3,31 per incontro) Cronologia della competizione 1980 1982 Manuale La Mestaruussarja 1981 fu la settantaduesima edizione della massima serie del campionato finl...

 

 

Graham NashGraham Nash nel 2023 Nazionalità Regno Unito Stati Uniti GenereFolkFolk rockSkiffle Periodo di attività musicale1962 – in attività Strumentovoce, chitarra, tastiere, pianoforte, armonica a bocca, percussioni Sito ufficiale Modifica dati su Wikidata · Manuale Graham William Nash (Blackpool, 2 febbraio 1942) è un cantautore, compositore e fotografo inglese naturalizzato statunitense. Indice 1 Carriera 1.1 Musica 2 Discografia 2.1 Con The Holli...

 

 

1962–present separatist conflict in Indonesian New Guinea For the earlier, colonial dispute, see West New Guinea dispute. Papua conflictPart of West New Guinea dispute and the Terrorism in Indonesia  Papua province   Highland Papua province  Central Papua province   South Papua province  West Papua province  Southwest Papua provinceDate1 October 1962 – present(61 years, 6 months and 22 days)LocationPredominantly in...

追晉陸軍二級上將趙家驤將軍个人资料出生1910年 大清河南省衛輝府汲縣逝世1958年8月23日(1958歲—08—23)(47—48歲) † 中華民國福建省金門縣国籍 中華民國政党 中國國民黨获奖 青天白日勳章(追贈)军事背景效忠 中華民國服役 國民革命軍 中華民國陸軍服役时间1924年-1958年军衔 二級上將 (追晉)部队四十七師指挥東北剿匪總司令部參謀長陸軍�...

 

 

Murad Iمراد اولHüdavendigârSultan UtsmaniyahBerkuasaMaret 1362 – 14 Juni 1389PendahuluOrhanPenerusBayezid IInformasi pribadiKelahiran29 Juni 1326Amasya,[1] Turki modernKematian15 Juni 1389(1389-06-15) (umur 62)KosovoPemakamanOrgan dalamnya dimakamkan di Meşhed-i Hüdâvendigâr, Kosovo[a]42°42′07″N 21°06′15″E / 42.70194°N 21.10417°E / 42.70194; 21.10417Koordinat: 42°42′07″N 21°06′15″E / 42.70194°N ...

 

 

Military occupation by Russia Russian occupation of Sumy OblastPart of the 2022 Russian invasion of UkraineSumy Oblast:   Ukrainian territory never occupied  Ukrainian territory liberated from occupation Native name Російська окупація Сумської областіРоссийская оккупация Сумской областиDate26 February 2022–7 April 2022 (1 month, 1 week and 5 days)LocationSumy Oblast, Ukraine The Russian ...

Computer file format DjVuFilename extensions .djvu, .djvInternet media type image/vnd.djvu, image/x-djvuMagic numberAT&TDeveloped byAT&T Labs – ResearchInitial release1998; 26 years ago (1998)Latest releaseVersion 26[1]April 2005; 19 years ago (2005-04) Type of formatImage file formatsContained byInterchange File FormatOpen format?Yes DjVu (/ˌdeɪʒɑːˈvuː/ DAY-zhah-VOO, like French déjà vu[2]) is a comput...

 

 

تحتاج النصوص المترجمة في هذه المقالة إلى مراجعة لضمان معلوماتها وإسنادها وأسلوبها ومصطلحاتها ووضوحها للقارئ، لأنها تشمل ترجمة اقتراضية أو غير سليمة. فضلاً ساهم في تطوير هذه المقالة بمراجعة النصوص وإعادة صياغتها بما يتناسب مع دليل الأسلوب في ويكيبيديا. تحتاج هذه المقالة �...

 

 

HectometreThe Great Pyramid of Giza is 137.7 metres high, which is 1.377 hectometres.General informationUnit systemSIUnit oflengthSymbolhmConversions 1 hm in ...... is equal to ...    SI base units   100 m   imperial/US units   109.36 yd 3937.0 in SI unit of length The hectometre (International spelling as used by the International Bureau of Weights and Measures; SI symbol: hm[1]) or hectom...

Movement in hip hop musicSee also: Golden age hip hopNew-school hip hopStylistic originsHip Hopold-school hip hopCultural originsEarly 1980s, Queens, Brooklyn, New York CityTypical instrumentsturntablesmicrophoneRoland TR-808SubgenresGolden age hip hopLocal scenesSouth Bronx, Brooklyn, Hollis, Queens, Jamaica, Queens The new school of hip hop was a movement in hip hop music, beginning in 1983–84 with the early records of Run–D.M.C., Whodini, and LL Cool J. Predominantly from Queens and Br...

 

 

Duta Besar Amerika Serikat untuk TiongkokSegel Kementerian Dalam Negeri Amerika SerikatDicalonkan olehPresiden Amerika SerikatDitunjuk olehPresidendengan nasehat Senat Berikut ini adalah daftar Duta Besar Amerika Serikat untuk Tiongkok Daftar Nama Potret Leonard Woodcock Arthur W. Hummel Jr. Winston Lord James Lilley J. Stapleton Roy Jim Sasser Joseph Prueher Clark T. Randt Jr. Jon Huntsman Jr. Gary Locke Max Baucus Terry Branstad Referensi United States Department of State: Background notes ...

 

 

 Vuelta a Burgos 2019Edizione41ª Data13 agosto - 17 agosto PartenzaBurgos ArrivoLagunas de Neila Percorso787 km, 5 tappe Tempo18h53'44 Media41,668 km/h Valida perUCI Europe Tour 2019 Classifica finalePrimo Iván Sosa Secondo Óscar Rodríguez Terzo Richard Carapaz Classifiche minoriPunti Alex Aranburu Montagna Iván Sosa Giovani Iván Sosa Squadre Team Ineos Cronologia Edizione precedenteEdizione successiva Vuelta a Burgos 2018Vuelta a Burgos 2020 Manuale La Vuelta a...

  關於如何在維基百科使用國際標準書號,請見「Help:各類書號」。此條目或許包含不重要、多餘或偏頗的範例。 (2015年4月14日)請協助改善條目,增加敘述,去除不太相关與过剩的範例。可参考更優秀條目寫作指南獲得更進一步資訊。此條目需要补充更多来源。 (2011年9月22日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。�...

 

 

Election in Vermont Main article: 1888 United States presidential election 1888 United States presidential election in Vermont ← 1884 November 6, 1888 1892 →   Nominee Benjamin Harrison Grover Cleveland Party Republican Democratic Home state Indiana New York Running mate Levi P. Morton Allen G. Thurman Electoral vote 4 0 Popular vote 45,192 16,788 Percentage 69.05% 25.65% County Results Harrison  60-70%  70-80%  80-9...

 

 

Manny Pacquiao Manny Pacquiao en 2011. Fiche d’identité Nom de naissance Emmanuel Dapidran Pacquiao Surnom Pac-Man Nationalité Philippines Naissance 17 décembre 1978 (45 ans)Bukidnon, Philippines Taille 1,66 m (5′ 5″) Catégorie Poids mouches à super-welters Palmarès Professionnel Amateur Combats 72 64 Victoires 62 60 Victoires par KO 39 Défaites 8 4 Matchs nuls 2 Titres professionnels Champion du monde poids mouches WBC (1998-1999) Champion du monde poids super-co...

Posterolateral sulcus of medulla oblongataHind- and mid-brains; postero-lateral view.Section of the medulla oblongata through the lower part of the decussation of the pyramids. Anterior median fissurePosterior median sulcusAnterior column (in red), with 3’, anterior rootPosterior column (in blue), with 4’, posterior rootsLateral cerebrospinal fasciculusPosterior funiculus The red arrow, a, a’, indicates the course the lateral cerebrospinal fasciculus takes at the level of the decussatio...

 

 

この記事は別の言語から大ざっぱに翻訳されたものであり、場合によっては不慣れな翻訳者や機械翻訳によって翻訳されたものかもしれません。 翻訳を改善してくださる方を募集しています。 オブジェクト図の例。 統一モデリング言語(UML)のオブジェクト図(オブジェクトず)は、特定の時点でのモデル化されたシステムの構造の完全なビューまたは部分的なビュ�...