提供来自 Qt 具有有用枚举和函数的全局对象。 更多...
import 语句: | import QtQml |
Qt
is a singleton type that provides utility functions, properties, and enums. Here is an example showing how to use this type:
import QtQuick 2.0 Text { color: Qt.rgba(1, 0, 0, 1) text: Qt.md5("hello, world") }
Qt 对象包含的枚举可用于
Qt 名称空间
。例如,可以访问
Qt::LeftButton
and
Qt::RightButton
枚举值如
Qt.LeftButton
and
Qt.RightButton
.
The Qt object also contains helper functions for creating objects of specific data types. This is primarily useful when setting the properties of an item when the property has one of the following types:
若
QtQuick
module has been imported, the following helper functions for creating objects of specific data types are also available for clients to use:
color
- 使用
Qt.rgba
(),
Qt.hsla
(),
Qt.darker
(),
Qt.lighter
() 或
Qt.tint
()
font
- 使用
Qt.font
()
vector2d
- 使用
Qt.vector2d
()
vector3d
- 使用
Qt.vector3d
()
vector4d
- 使用
Qt.vector4d
()
quaternion
- 使用
Qt.quaternion
()
matrix4x4
- 使用
Qt.matrix4x4
()
The Qt object contains several functions for formatting QDateTime , QDate and QTime 值。
The format specification is described at Qt.formatDateTime .
The following functions on the global object allow you to dynamically create QML items from files or strings. See 从 JavaScript 动态创建 QML 对象 for an overview of their use.
The following functions are also on the Qt object.
application : 应用程序 |
The
application
object provides access to global application state properties shared by many QML components.
It is the same as the 应用程序 singleton.
以下范例使用
application
object to indicate whether the application is currently active:
import QtQuick Rectangle { width: 300; height: 55 color: Qt.application.active ? "white" : "lightgray" Text { text: "Application " + (Qt.application.active ? "active" : "inactive") opacity: Qt.application.active ? 1.0 : 0.5 anchors.centerIn: parent } }
注意: When using QML without a QGuiApplication , the following properties will be undefined:
inputMethod : InputMethod |
It is the same as the InputMethod singleton.
The
inputMethod
object allows access to application's
QInputMethod
object and all its properties and slots. See the
QInputMethod
文档编制进一步了解细节。
platform : 对象 |
The
platform
对象提供底层平台的有关信息。
Its properties are:
platform.os
|
This read-only property contains the name of the operating system. Possible values are:
|
platform.pluginName
|
This is the name of the platform set on the QGuiApplication instance as returned by QGuiApplication::platformName () |
styleHints : 对象 |
The
styleHints
object provides platform-specific style hints and settings. See the
QStyleHints
文档编制进一步了解细节。
You should access StyleHints via Application::styleHints 代替。
注意:
The
styleHints
object is only available when using the Qt Quick module.
uiLanguage : string |
The uiLanguage holds the name of the language to be used for user interface string translations. It is exposed in C++ as QQmlEngine::uiLanguage property.
You can set the value freely and use it in bindings. It is recommended to set it after installing translators in your application. By convention, an empty string means no translation from the language used in the source code is intended to occur.
若正使用 QQmlApplicationEngine and the value changes, QQmlEngine::retranslate () will be called.
callLater ( function ) |
callLater ( function , argument1 , argument2 , ...) |
Use this function to eliminate redundant calls to a function or signal.
The function passed as the first argument to Qt. callLater () will be called later, once the QML engine returns to the event loop.
When this function is called multiple times in quick succession with the same function as its first argument, that function will be called only once.
例如:
import QtQuick Rectangle { width: 480 height: 320 property int callsToUpdateMinimumWidth: 0 property bool optimize: true property int currentTextModel: 0 property var columnTexts: [ ["Click on either", "rectangle above", "and note how the counter", "below updates", "significantly faster using the", "regular (non-optimized)", "implementation"], ["The width", "of this column", "is", "no wider than the", "widest item"], ["Note how using Qt.callLater()", "the minimum width is", "calculated a bare-minimum", "number", "of times"] ] Text { x: 20; y: 280 text: "Times minimum width has been calculated: " + callsToUpdateMinimumWidth } Row { y: 25; spacing: 30; anchors.horizontalCenter: parent.horizontalCenter Rectangle { width: 200; height: 50; color: "lightgreen" Text { text: "Optimized behavior\nusing Qt.callLater()"; anchors.centerIn: parent } MouseArea { anchors.fill: parent; onClicked: { optimize = true; currentTextModel++ } } } Rectangle { width: 200; height: 50; color: "lightblue" Text { text: "Regular behavior"; anchors.centerIn: parent} MouseArea { anchors.fill: parent; onClicked: { optimize = false; currentTextModel++ } } } } Column { id: column anchors.centerIn: parent onChildrenChanged: optimize ? Qt.callLater(updateMinimumWidth) : updateMinimumWidth() property int widestChild function updateMinimumWidth() { callsToUpdateMinimumWidth++ var w = 0; for (var i in children) { var child = children[i]; if (child.implicitWidth > w) { w = child.implicitWidth; } } widestChild = w; } Repeater { id: repeater model: columnTexts[currentTextModel%3] delegate: Text { color: "white" text: modelData width: column.widestChild horizontalAlignment: Text.Center Rectangle { anchors.fill: parent; z: -1; color: index%2 ? "gray" : "darkgray" } } } } }
Any additional arguments passed to Qt. callLater () will be passed on to the function invoked. Note that if redundant calls are eliminated, then only the last set of arguments will be passed to the function.
string QT_TRANSLATE_NOOP ( string context , string sourceText , string disambiguation ) |
Marks sourceText for dynamic translation in the given context ; i.e, the stored sourceText will not be altered.
若相同 sourceText is used in different roles within the same translation context, an additional identifying string may be passed in for disambiguation .
返回 sourceText .
QT_TRANSLATE_NOOP is used in conjunction with the dynamic translation functions
qsTr
() 和
qsTranslate
(). It identifies a string as requiring translation (so it can be identified by
lupdate
), but leaves the actual translation to the dynamic functions.
范例:
Item { property string greeting: QT_TRANSLATE_NOOP("CustomContext", "hello") Text { text: qsTranslate("CustomContext", greeting) } }
另请参阅 Qt 国际化 .
Marks id for dynamic translation.
返回 id .
QT_TRID_NOOP is used in conjunction with the dynamic translation function
qsTrId
(). It identifies a string as requiring translation (so it can be identified by
lupdate
), but leaves the actual translation to
qsTrId
().
范例:
Item { property string greetingId: QT_TRID_NOOP("hello_id") Text { text: qsTrId(greetingId) } }
string QT_TR_NOOP ( string sourceText , string disambiguation ) |
Marks sourceText for dynamic translation; i.e, the stored sourceText will not be altered.
若相同 sourceText is used in different roles within the same translation context, an additional identifying string may be passed in for disambiguation .
返回 sourceText .
QT_TR_NOOP is used in conjunction with the dynamic translation functions
qsTr
() 和
qsTranslate
(). It identifies a string as requiring translation (so it can be identified by
lupdate
), but leaves the actual translation to the dynamic functions.
范例:
Item { property string greeting: QT_TR_NOOP("hello") Text { text: qsTr(greeting) } }
另请参阅 Qt 国际化 .
返回 baseColor with an alpha value of value .
value is a real ranging from 0 (completely transparent) to 1 (completely opaque).
string atob ( data ) |
ASCII to binary - this function decodes the base64 encoded data string and returns it.
binding ( function ) |
返回 JavaScript 对象表示 特性绑定 ,采用 function that evaluates the binding.
There are two main use-cases for the function: firstly, to apply a property binding imperatively from JavaScript code:
Item { property bool someCondition: true property int edgePosition Component.onCompleted: { if (someCondition == true) { // bind to the result of the binding expression passed to Qt.binding() edgePosition = Qt.binding(function() { return x + width }) } } }
and secondly, to apply a property binding when initializing property values of dynamically constructed objects (via Component.createObject () 或 Loader.setSource ()).
For example, assuming the existence of a DynamicText component:
import QtQuick Text { id: textElement width: 200 height: 200 text: "Default text" property string dynamicText: "Dynamic text" onTextChanged: console.log(text) }
the output from:
Item { id: root property string dynamicText: "Root text" Component.onCompleted: { var c = Qt.createComponent("DynamicText.qml") var obj1 = c.createObject(root, { 'text': Qt.binding(function() { return dynamicText + ' extra text' }) }) root.dynamicText = "Modified root text" var obj2 = c.createObject(root, { 'text': Qt.binding(function() { return this.dynamicText + ' extra text' }) }) obj2.dynamicText = "Modified dynamic text" } }
and from:
Item { id: root property string dynamicText: "Root text" Loader { id: loaderOne onLoaded: root.dynamicText = "Modified root text" } Loader { id: loaderTwo onLoaded: item.dynamicText = "Modified dynamic text" } Component.onCompleted: { loaderOne.setSource("DynamicText.qml", { 'text': Qt.binding(function() { return dynamicText + ' extra text' }) }) loaderTwo.setSource("DynamicText.qml", { 'text': Qt.binding(function() { return this.dynamicText + ' extra text' }) }) } }
should both be:
Root text extra text Modified root text extra text Dynamic text extra text Modified dynamic text extra text
This function cannot be used in property binding declarations (see the documentation on binding declarations and binding assignments ) except when the result is stored in an array bound to a var property.
Item { width: 50 property var storedBindings: [ Qt.binding(function() { return x + width }) ] // stored property int a: Qt.binding(function() { return x + width }) // error! property int b Component.onCompleted: { b = storedBindings[0] // causes binding assignment } }
string btoa ( data ) |
Binary to ASCII - this function returns a base64 encoding of data .
Returns the color corresponding to the given
name
(i.e. red or #ff0000). If there is no such color,
null
被返回。
返回
true
if both
lhs
and
rhs
yield equal color values. Both arguments may be either color values or string values. If a string value is supplied it must be convertible to a color, as described for the
color
value type.
Component createComponent ( url url , enumeration mode , QtObject parent ) |
返回
Component
object created using the QML file at the specified
url
,或
null
if an empty string was given.
The returned component's
Component::status
property indicates whether the component was successfully created. If the status is
Component.Error
,见
Component::errorString
() for an error description.
若可选
mode
parameter is set to
Component.Asynchronous
, the component will be loaded in a background thread. The
Component::status
property will be
Component.Loading
while it is loading. The status will change to
Component.Ready
if the component loads successfully, or
Component.Error
if loading fails. This parameter defaults to
Component.PreferSynchronous
if omitted.
若
mode
被设为
Component.PreferSynchronous
, Qt will attempt to load the component synchronously, but may end up loading it asynchronously if necessary. Scenarios that may cause asynchronous loading include, but are not limited to, the following:
若可选 parent parameter is given, it should refer to the object that will become the parent for the created Component object. If no mode was passed, this can be the second argument.
调用 Component.createObject () on the returned component to create an object instance of the component.
例如:
import QtQuick Item { id: container width: 300; height: 300 function loadButton() { var component = Qt.createComponent("Button.qml"); if (component.status == Component.Ready) { var button = component.createObject(container); button.color = "red"; } } Component.onCompleted: loadButton() }
见 从 JavaScript 动态创建 QML 对象 for more information on using this function.
To create a QML object from an arbitrary string of QML (instead of a file), use Qt.createQmlObject ().
Component createComponent ( string moduleUri , string typeName , enumeration mode , QtObject parent ) |
这是重载函数。
返回 Component object created for the type specified by moduleUri and typeName .
import QtQuick QtObject { id: root property Component myComponent: Qt.createComponent("QtQuick", "Rectangle", Component.Asynchronous, root) }
This overload mostly behaves as the
url
based version, but can be used to instantiate types which do not have an URL (e.g. C++ types registered via
QML_ELEMENT
).
注意:
In some cases, passing
Component.Asynchronous
won't have any effect:
若可选 parent parameter is given, it should refer to the object that will become the parent for the created Component object. If no mode was passed, this can be the second argument.
对象 createQmlObject ( string qml , 对象 parent , string filepath ) |
Returns a new object created from the given
qml
string which will have the specified
parent
,或
null
if there was an error in creating the object.
若 filepath is specified, it will be used for error reporting for the created object.
Example (where
parentItem
is the id of an existing QML item):
const newObject = Qt.createQmlObject(` import QtQuick Rectangle { color: "red" width: 20 height: 20 } `, parentItem, "myDynamicSnippet" );
In the case of an error, a
QQmlError
object is thrown. This object has an additional property,
qmlErrors
, which is an array of the errors encountered. Each object in this array has the members
lineNumber
,
columnNumber
,
fileName
and
message
. For example, if the above snippet had misspelled color as 'colro' then the array would contain an object like the following: { "lineNumber" : 1, "columnNumber" : 32, "fileName" : "dynamicSnippet1", "message" : "Cannot assign to non-existent property "colro""}.
注意: This function returns immediately, and therefore may not work if the qml string loads new components (that is, external QML files that have not yet been loaded). If this is the case, consider using Qt.createComponent () 代替。
警告: This function is extremely slow since it has to compile the passed QML string every time it is invoked. Furthermore, it's very easy to produce invalid QML when programmatically constructing QML code. It's much better to keep your QML components as separate files and add properties and methods to customize their behavior than to produce new components by string manipulation.
见 从 JavaScript 动态创建 QML 对象 for more information on using this function.
Returns a color darker than baseColor 通过 factor provided.
If the factor is greater than 1.0, this function returns a darker color. Setting factor to 3.0 returns a color that has one-third the brightness. If the factor is less than 1.0, the return color is lighter, but we recommend using the Qt. lighter () function for this purpose. If the factor is 0 or negative, the return value is unspecified.
The function converts the current RGB color to HSV, divides the value (V) component by factor and converts the color back to RGB.
若 factor is not supplied, returns a color that is 50% darker than baseColor (factor 2.0).
exit ( int retCode ) |
此函数导致 QQmlEngine::exit (int) signal to be emitted. Within the qml tool , this causes the launcher application to exit with the specified return code ( retCode ). To exit from the event loop with a specified return code when this method is called, a C++ application can connect the QQmlEngine::exit (int) signal to the QCoreApplication::exit (int) slot.
另请参阅 quit ().
font font ( 对象 fontSpecifier ) |
Returns a font with the properties specified in the fontSpecifier object or the nearest matching font. The fontSpecifier object should contain key-value pairs where valid keys are the font type's subproperty names, and the values are valid values for each subproperty. Invalid keys will be ignored.
Returns a list of the font families available to the application.
string formatDate ( datetime date , variant format , variant localeFormatOption ) |
Returns a string representation of date , optionally formatted using format .
The
date
parameter may be a JavaScript
Date
对象,
date
特性,
QDate
,或
QDateTime
值。
format
and
localeFormatOption
parameter may be any of the possible format values as described for
Qt.formatDateTime
().
若 format 未指定, date is formatted using Locale.ShortFormat 使用默认区域设置。
另请参阅 Locale .
string formatDateTime ( datetime dateTime , variant format , variant localeFormatOption ) |
Returns a string representation of dateTime , optionally formatted using format and localeFormatOption .
The
dateTime
parameter may be a JavaScript
Date
对象,
date
特性,
QDate
,
QTime
,或
QDateTime
值。
若 format is not provided, dateTime is formatted using Locale.ShortFormat using the default locale. Otherwise, format should be either:
Qt.RFC2822Date
or
Qt.ISODate
.
locale
对象。
若 format specifies a locale object, dateTime is formatted with QLocale::toString . In this case, localeFormatOption can hold a value of type QLocale::FormatType to further tune the formatting. If none is provided, Locale.ShortFormat 被使用。
若 format specifies a format string, it should use the following expressions to specify the date:
表达式 | 输出 |
---|---|
d | the day as number without a leading zero (1 to 31) |
dd | the day as number with a leading zero (01 to 31) |
ddd | the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName(). |
dddd | the long localized day name (e.g. 'Monday' to ' Qt::Sunday '). Uses QDate::longDayName(). |
M | the month as number without a leading zero (1-12) |
MM | the month as number with a leading zero (01-12) |
MMM | the abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName(). |
MMMM | the long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName(). |
yy | the year as two digit number (00-99) |
yyyy | the year as four digit number |
In addition the following expressions can be used to specify the time:
表达式 | 输出 |
---|---|
h | the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display) |
hh | the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display) |
m | the minute without a leading zero (0 to 59) |
mm | the minute with a leading zero (00 to 59) |
s | the second without a leading zero (0 to 59) |
ss | the second with a leading zero (00 to 59) |
z | the milliseconds without leading zeroes (0 to 999) |
zzz | the milliseconds with leading zeroes (000 to 999) |
AP | use AM/PM display. AP will be replaced by either "AM" or "PM". |
ap | use am/pm display. ap will be replaced by either "am" or "pm". |
t | include a time-zone indicator. |
All other input characters will be ignored. Any sequence of characters that are enclosed in single quotes will be treated as text and not be used as an expression. Two consecutive single quotes ("''") are replaced by a single quote in the output.
For example, if the following date/time value was specified:
// 21 May 2001 14:13:09 var dateTime = new Date(2001, 5, 21, 14, 13, 09)
This
dateTime
value could be passed to
Qt.formatDateTime()
,
Qt.formatDate
() 或
Qt.formatTime
() 采用
format
values below to produce the following results:
格式 | 结果 |
---|---|
"dd.MM.yyyy" | 21.05.2001 |
"ddd MMMM d yy" | Tue May 21 01 |
"hh:mm:ss.zzz" | 14:13:09.042 |
"h:m:s ap" | 2:13:9 pm |
另请参阅 Locale .
string formatTime ( datetime time , variant format , variant localeFormatOption ) |
Returns a string representation of time , optionally formatted using format , and, if provided, localeFormatOption .
The
time
parameter may be a JavaScript
Date
对象,
QTime
,或
QDateTime
值。
format
and
localeFormatOption
parameter may be any of the possible format values as described for
Qt.formatDateTime
().
若 format 未指定, time is formatted using Locale.ShortFormat 使用默认区域设置。
另请参阅 Locale .
color hsla ( real hue , real saturation , real lightness , real alpha ) |
Returns a color with the specified hue , saturation , lightness ,和 alpha components. All components should be in the range 0-1 (inclusive).
color hsva ( real hue , real saturation , real value , real alpha ) |
Returns a color with the specified hue , saturation , value and alpha components. All components should be in the range 0-1 (inclusive).
bool isQtObject ( object ) |
返回
true
if
object
is a valid reference to a Qt or QML object,
false
否则。
Returns a color lighter than baseColor 通过 factor provided.
If the factor is greater than 1.0, this functions returns a lighter color. Setting factor to 1.5 returns a color that is 50% brighter. If the factor is less than 1.0, the return color is darker, but we recommend using the Qt. darker () function for this purpose. If the factor is 0 or negative, the return value is unspecified.
The function converts the current RGB color to HSV, multiplies the value (V) component by factor and converts the color back to RGB.
若 factor is not supplied, returns a color that is 50% lighter than baseColor (factor 1.5).
locale ( name ) |
Returns a JS object representing the locale with the specified name , which has the format "language[_territory][.codeset][@modifier]" or "C", where:
语言
is a lowercase, two-letter, ISO 639 language code,
territory
is an uppercase, two-letter, ISO 3166 country code, and
codeset
and
modifier
被忽略。
If the string violates the locale format, or language is not a valid ISO 369 code, the "C" locale is used instead. If country is not present, or is not a valid ISO 3166 code, the most appropriate country is chosen for the specified language.
另请参阅 Locale .
string md5 ( data ) |
Returns a hex string of the md5 hash of data .
matrix4x4 matrix4x4 () |
Returns an identity matrix4x4.
Returns a matrix4x4 with the specified 值 . 值 is expected to be a JavaScript array with 16 entries.
The array indices correspond to positions in the matrix as follows:
0 | 1 | 2 | 3 |
4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 |
matrix4x4 matrix4x4 ( real m11 , real m12 , real m13 , real m14 , real m21 , real m22 , real m23 , real m24 , real m31 , real m32 , real m33 , real m34 , real m41 , real m42 , real m43 , real m44 ) |
Returns a matrix4x4 with the specified values.
The arguments correspond to their positions in the matrix:
m11 | m12 | m13 | m14 |
m21 | m22 | m23 | m24 |
m31 | m32 | m33 | m34 |
m41 | m42 | m43 | m44 |
Attempts to open the specified
target
url in an external application, based on the user's desktop preferences. Returns
true
if it succeeds,
false
否则。
警告:
A return value of
true
indicates that the application has successfully requested the operating system to open the URL in an external application. The external application may still fail to launch or fail to open the requested URL. This result will not be reported back to the application.
Returns a point with the specified x and y 坐标。
string qsTr ( string sourceText , string disambiguation , int n ) |
返回翻译版本的 sourceText ,可选基于 disambiguation 字符串和值 n 对于包含多个的字符串;否则返回 sourceText itself if no appropriate translated string is available.
若相同 sourceText is used in different roles within the same translation context, an additional identifying string may be passed in for disambiguation .
范例:
Text { text: qsTr("hello") }
另请参阅 Qt 国际化 .
Returns a translated string identified by id . If no matching string is found, the id itself is returned. This should not happen under normal conditions.
若
n
>= 0, all occurrences of
%n
in the resulting string are replaced with a decimal representation of
n
. In addition, depending on
n
's value, the translation text may vary.
范例:
Text { text: qsTrId("hello_id") }
It is possible to supply a source string template like:
//% <string>
or
\begincomment% <string> \endcomment
范例:
Text { //% "hello" text: qsTrId("hello_id") }
Creating binary translation (QM) files suitable for use with this function requires passing the
-idbased
选项到
lrelease
工具。
另请参阅 QT_TRID_NOOP () 和 Qt 国际化 .
string qsTranslate ( string context , string sourceText , string disambiguation , int n ) |
返回翻译版本的 sourceText 在给定 context ,可选基于 disambiguation 字符串和值 n 对于包含多个的字符串;否则返回 sourceText itself if no appropriate translated string is available.
若相同 sourceText is used in different roles within the same translation context , an additional identifying string may be passed in for disambiguation .
范例:
Text { text: qsTranslate("CustomContext", "hello") }
另请参阅 Qt 国际化 .
quaternion quaternion ( real scalar , real x , real y , real z ) |
Returns a quaternion with the specified scalar , x , y ,和 z 值。
quit () |
此函数导致 QQmlEngine::quit () signal to be emitted. Within the qml tool , this causes the launcher application to exit; to quit a C++ application when this method is called, connect the QQmlEngine::quit () 信号到 QCoreApplication::quit () 槽。
另请参阅 exit ().
Returns a rect with the top-left corner at x , y and the specified width and height .
返回 url resolved relative to the URL of the caller.
If there is no caller or the caller is not associated with a QML context, returns url resolved relative to the QML engine's base URL. If the QML engine has no base URL, just returns url .
另请参阅 url ().
返回 url resolved relative to the URL of the QML context of context 。若 context is not associated with a QML context, returns url resolved relative to the QML engine's base URL. If the QML engine has no base URL, just returns url .
另请参阅 url ().
color rgba ( real red , real green , real blue , real alpha ) |
Returns a color with the specified red , green , blue ,和 alpha components. All components should be in the range 0-1 (inclusive).
Returns a size with the specified width and height .
This function allows tinting one color ( baseColor ) with another ( tintColor ).
The tint color should usually be mostly transparent, or you will not be able to see the underlying color. The below example provides a slight red tint by having the tint color be pure red which is only 1/16th opaque.
Item { Rectangle { x: 0; width: 80; height: 80 color: "lightsteelblue" } Rectangle { x: 100; width: 80; height: 80 color: Qt.tint("lightsteelblue", "#10FF0000") } }
Tint is most useful when a subtle change is intended to be conveyed due to some event; you can then use tinting to more effectively tune the visible color.
返回
url
verbatim. This can be used to force a type coercion to
url
. In contrast to Qt.
resolvedUrl
() this retains any relative URLs. As strings are implicitly converted to urls, the function can be called with a string as argument, and will then return a url.
另请参阅 resolvedUrl ().
Returns a vector2d with the specified x and y 值。
Returns a vector3d with the specified x , y ,和 z 值。
Returns a vector4d with the specified x , y , z ,和 w 值。