QML Syntax - Basics

Qt Quick introduces a scripting language called QML (Qt Meta/Modeling Language) for Qt, which is the implementation of the ECMAScript standard. So QML syntax is implemented on the basis of ECMAScript syntax.

The ECMAScript language standard is tempered and defined by Netscape, Sun, Microsoft, Borland and other companies based on JavaScript and JScript.

ECMAScript is just a description, defining all properties, methods and objects of the scripting language. Other languages ​​can implement ECMAScript as a basis for functionality, just as JavaScript does. This implementation can be extended to include new features specific to the host environment. For example, QML introduces signals and slots in the Qt object system, and adds very distinctive new features such as dynamic property binding.

As a brand new programming language, QML has three cores:

  • ECMAScript
  • Qt object system
  • Qt Quick standard library

The benefits of this article, the fee to receive Qt development learning materials package, technical video, including (C++ language foundation, Qt programming introduction, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓ See below

1. Grammar

Let's look at the syntax of ECMAScript one by one. (QML is the implementation of the ECMAScript standard, so the syntax of the two is basically the same)

1. Case Sensitivity

As in C++, variables, function names, operators, and everything else are case-sensitive, that is, the variables area and Area are different.

2. Weak typing

Unlike C++, variables in ECMAScript do not have a specific type. When defining a variable, only the var operator is used, and it can be initialized to any value. You can change the data type stored by the variable at any time (in fact, you should try to avoid doing this). For example:

var i = 0
console.log(i)
i = "hello"
console.log(i)

Although there is no problem syntactically to do so, good coding practice is for a variable to always hold a value of the same type.

3. The semicolon after the statement is optional

Languages ​​such as C, C++, and Java require each statement to end with a semicolon (;). ECMAScript allows developers to decide whether to end a line of code with a semicolon. Without the semicolon, ECMAScript treats the end of the line as the end of the statement (similar to Lua, Python, Visual Basic). As for whether to add a semicolon, it depends on your preference. Both of the following lines of code are syntactically correct:

var background = "white"
var i = 0

2. Variables

The var operator is used to declare variables in ECMAScript. Similar to C++, variable names need to follow certain rules.

1. Variable declaration

Variables are defined using the var operator followed by the variable name. For example:

var i = 0

In this example, the variable i is declared and initialized to 0. You can also not initialize it, and then initialize it when it is used.

A var statement can define multiple variables. For example:

var i = 0 , name = "j"

This example defines the variable i, initialized to a number; also defines the variable name, initialized to a string. You see, unlike C++ or Java, multiple variables defined by a var statement can have different types.

2. Variable naming rules

Variable naming needs to follow two simple rules:

  • The first character must be a letter, an underscore (_), or a dollar sign ($).
  • The remaining characters can be underscores, dollar signs, or any alphanumeric characters.

The following variable names are legal:

var test
var objectName
var —phone
var $1

For the readability of the code, a certain naming style should also be followed when naming variables. Because Qt is a C++-based application framework, and QML is a part of the Qt framework, it is recommended to use the same naming style as Qt C++ code - camel case.

For variables (including function names), start with a lowercase letter and use camel case between words. For class names, start with a capital letter and use camel case between words.

Three, the original type

ECMAScript has 5 primitive types namely Undefined, Null, Boolean, Number and String. Each primitive type defines the range of values ​​it contains and its literal representation.

ECMAScript provides the typeof operator to determine the type of a value. If the value is a primitive type, typeof will return its specific type name; and if the value is a reference value, then typeof will uniformly return "object" as the type name. Examples are as follows:

import QtQuick 2.2

Rectangle {
	Component.onCompleted:{
		var name = "Zhang San Feng"
        console.log(typeof name) // 输出:qml:string
        console.log(typeof 60) // 输出:qml:number
	}
}

The type of the variable name is string, and the type of the literal 60 is number. Among them, "qml:" is the prefix carried when using console.log to output information.

1. Undefined type

The Undefined type has only one value, undefined. When a declared variable is not initialized, the default value of the variable is undefined. For example:

var temp

The above code declares the variable temp but does not explicitly initialize it, its value will be set to undefined, which is different from C++. This feature of ECMAScript: uninitialized variables also have a fixed initial value, we can compare a variable with undefined to implement some business logic. for example:

var runOnce;
...
if(runOnce == undefined) {
    runOnce = true
}
else {
    ...
}

When the function does not have a clear return value, the returned value is also undefined, as shown below:

function blankFunc(){}
console.log(blankFunc() == undefined) // 输出:true

2. Null type

The Null type also has only one value, null.

You can explicitly initialize a variable to null and implement some logic accordingly.

3. Boolean type

Boolean is one of the most commonly used types in ECMAScript, it has two values ​​true and false.

4. Number type

The Number type is the most special, it can represent both 32-bit integers and 64-bit floating-point numbers. Any numbers you enter directly in QML code are treated as literals of type Number.

The following code declares a variable that holds an integer value:

var integer = 10

The maximum value of the number type is Number.MAX_VALUE, and the minimum value is Number.MlN_VALUE, which define the outer boundary of the Number value, and all ECMAScript numbers must be between these two values.

5. String type

The String type in ECMAScript exists as a primitive type, which stores Unicode characters, and the corresponding Qt C++ type is QString. When you mix C++ and QML programming, all variables of type QString will be mapped to String in ECMAScript.

String literals can be declared with double quotes (") or single quotes ('). In Qt, only double quotes and single quotes are used to represent characters. For consistency, it is recommended that you not use single quotes to represent strings. There is no character type in ECMAScript, which is why you can use single quotes to represent strings. The following two lines of code are valid:

var name = 'Lv Bu'
var name = "Guan Yu"

Four, type conversion

It is unimaginable that a programming language does not support type conversion. In ECMAScript, type conversion is very simple.

1. Convert to string

The three primitive types Boolean, Number, and String all have toString() methods, which can convert their values ​​into strings. For example, the following code can run normally in Qt:

var name = "Zhang San Feng"
console.log(name.toString())
console.log(true.toString())
var visible = false
console.log(visible.toString())
var integer = 3.14159
console.log(integer.toString())

The toString() method of the Number type can also be converted by base, for example:

var integer = 13
console.log (integer.toString(16)) // 输出: D

If you do not specify the number base, toString() will output in decimal no matter what form the Number type is originally declared in.

2. Convert to Number

parselnt() and parseFloat() can convert non-numeric original values ​​into numbers, the former converts the value into an integer, and the latter converts the value into a floating-point number. These two methods can only be used for String type, if you call them for other types, the return value will be weird NaN.

parselnt() and parseFloat() will scan the string until the first non-numeric character is encountered, and return the result of the conversion. For example parselnt("2014") will return 2014. For parseFloat(), the first decimal point is considered a valid character, while parselnt() does not.

Here are some examples:

var numl = parselnt ("2014 年") // 输出:2014
var num2 = parselnt ("OxC") // 输出:12
var num3 = parselnt ("3.14") // 输出:3
var num4 = parselnt ("green") // 输出:NaN_
var num5 = parseFloat ("3.14159") // 输出:3.14159
var num7 = parseFloat ("Am I Float") // 输出:NaN

parselnt() also supports base patterns, here are some examples:

var numl = parselnt ("AK47", 16) // 输出:10
var num2 = parselnt ("AK47", 10) // 输出:NaN
var num3 = parselnt ("010", 8) // 输出:8
var nun4 = parselnt ("010", 10) // 输出:10

It should be noted that the string representing the floating-point number must be expressed in decimal form, such as parseFloat("OxFE"), returning NaN.

3. Mandatory type conversion

If you are a C/C++ programmer, you must have a love-hate relationship with casts. ECMAScript also supports mandatory type conversion, there are three conversions:

  • Boolean(value), convert value to Boolean type.
  • Number(value), convert value to a number (integer or floating point).
  • String(value), convert value into a string.

Five, function

Functions in ECMAScript are named, reusable blocks of code. Also, ECMAScript does not support function overloading.

1. Function syntax

The function syntax is as follows:

function functionName(arg1, arg2, ..., argN){
	// 要执行的代码
}

function is a keyword that must be used when defining a function. functionName can be chosen arbitrarily, as long as it conforms to the variable naming rules. arg1 to argN are the parameters of the function, of course there can be no parameters. Inside the curly braces is a block of code to be executed.

Example of a parameterless function:

function quitApp(){
	Qt .quit ();
}

Example of a function with parameters:

function showError(msg){
	console.log("error - ", msg);
}

function travel(country, city){
	console.log("Welcome to ", city, " , ", country);
}

When we use function parameters, parameters are like variable declarations without the var operator. This is in contrast to C++ where function parameters must be typed.

2. The return value of the function

The functions in ECMAScript have a return value by default, even if you do not explicitly use the return statement, it will return undefined. If you want to return the result of a function operation to the place where it was called, you can use the return statement. Here is a simple example:

function add(numberl, number2){
	var result = number1 + number2;
	console.log(number1, "+" ,number2, result);
	return result;
}

You can call the add() function like this: var ret = add(100, 34);.

6. Operators

The operators of ECMAScript are similar to those of C++, Java and other languages, and the specific content will not be repeated here. Only the keyword operators are highlighted here . void, typeof, instanceof, new, delete These are keyword operators.

  • The void operator is special. It is placed before an expression, discards the value of the expression, and returns undefined.
  • As mentioned earlier, typeof returns the original type for a primitive value, and returns object for a reference value. This makes you unable to accurately determine the reference type of an object, so ECMAScript introduces the instanceof operator.
  • instanceof is used to test the actual type of an object, you need to explicitly specify the type to test. For example:
  • var str = new String ("hello world"); console.log (str instanceof String); // 输出:true
  • The new operator is used to create an object, which has been used many times before, so I won't repeat it here. The delete operator is quite special. In QML, generally it can only delete the properties defined by you in an object, but most of the core properties defined by the framework cannot be deleted by you. When we call delete in ECMAScript, we dereference the object most of the time, lest someone keep referencing an object and let it get away with it.

Seven, use the console

The console provides functions such as outputting log information, assertions, timers, counters, and performance analysis. Here we only introduce the first three functions that we often use.

1. Output log information

The console object provides several methods for printing debugging information:

  • console.log();
  • console.debug();
  • console.info();console.warn();
  • console.error();

2. Affirmations

console.assert() provides an assertion function, it accepts an expression, when the value of the expression is false, it will output debugging information and print the line where the QML is located. For example: console.assert(false).

If you pass additional arguments to console.assert(), it will output them to the console. Example:

var years = 0;

for (; years < 18; years++){
	console.log("I\'m minor"); 
    continue;
	console.log ("You shoult not see me"};
}

console.assert(years < 18, years);

The assert statement above will output the following information:

18
onCompleted (file:///F:/projects/qtquick/qmls/show_type.qml:187)

It should be noted that in QML, using console.assert(), if the assertion fails, the program will not terminate.

3. Timer

The console provides a timer function, which is convenient for us to measure the time consumption of some codes.

console.time(tag) Start the timer, the tag of string type is required. console.timeEnd(tag) Stop the timer, and output the time-consuming information corresponding to a certain tag on the console. tag is required. Here's a simple example:

console.time("regexp");

var str = "We are dogs;\nYour dogs;\nWe want meat.\nPlease.";
var lines = str.match(/^We.*/mg);
console.log(lines.length);
console.log(lines);
console.timeEnd("regexp");

// 输出:regexp: 7ms

The article is transferred from the blog garden (fengMisaka): [QML Quick Start] QML Grammar - Basics

The benefits of this article, the fee to receive Qt development learning materials package, technical video, including (C++ language foundation, Qt programming introduction, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓ See below

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131904108