string QML Value Type
一个自由格式的文本字符串。更多...
| Since: | Qt 6.12 |
详细说明
string 类型指用引号括起的自由格式文本字符串,例如“Hello world!”。QML语言默认提供此值类型。
示例:
Text { text: "Hello world!" }string 类型的属性默认值为空。
字符串具有一个length 属性,用于存储字符串中的字符数。
字符串值类型由 C++ 类型 `QString` 支持。它继承了 JavaScript 的 String 基本类型,不仅提供了大部分相同的 API,还增加了一些额外的方法。例如,QML 字符串值类型的方法 `arg() ` 支持值替换:
var message = "There are %1 items"
var count = 20
console.log(message.arg(count)) // "There are 20 items"arg() 方法还支持多个参数,允许您在单次调用中替换多个占位符:
var message = "%1 of %2 files copied. Errors: %3"
console.log(message.arg(5, 7, 0)) // "5 of 7 files copied. Errors: 0"使用多个参数比连续调用 `arg() ` 更高效,并且可以避免参数本身包含占位符时可能出现的问题:
var result = "%1 %2".arg("%1f", "Hello") // "%1f Hello" (correct)
// Compare with chained calls:
var result = "%1 %2".arg("%1f").arg("Hello") // "Hellof %2" (incorrect)QML 字符串值类型支持大多数 ECMAScript 字符串功能,例如模板(字符串)字面量、字符串插值、多行字符串以及字符串循环。
总体而言,QML 字符串支持大多数 JavaScript String 方法,包括使用string.includes() 、string.startsWith() 和string.endsWith() 检查是否包含;使用string.repeats() 重复字符串;以及使用string.slice() 和string.split() 进行切片和拆分。
有关 QML 支持的 ECMAScript 版本的更多信息,请参阅JavaScript 宿主环境
有关 JavaScript 字符串方法的更多信息,请参阅mdn JavaScript 字符串
在与 C++ 集成时,请注意,从 C++ 传递到 QML 的任何QString 值都会自动转换为string 值,反之亦然。
另请参阅 QML 值类型和ECMAScript 语言规范。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.