Conversión de cadenas y números QML

Cadena convertida en número

En el código QML, si encuentra una cadena en un número, puede usar Número (str) para convertir str en un tipo de número

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    
    
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property string testStr: "-100000"
    property int testInt: 44
    property double testDouble: 11.11
    property string testDoubleStr: "22.34432"
    Text {
    
    
        id: intTxt
        text: testInt * 2
        anchors.top: parent.top
        anchors.left: parent.left
        width: parent.width
        height: 20
    }
    Text {
    
    
        id: doubleTxt
        text: testDouble
        anchors.top: intTxt.bottom
        anchors.left: parent.left
        width: parent.width
        height: 20

    }
    MouseArea {
    
    
        anchors.fill: parent
        onClicked: {
    
    
            testInt = Number(testStr)
            testDouble = Number(testDoubleStr)
        }
    }
}

Después de ejecutar la
Inserte la descripción de la imagen aquí
máquina independiente, se convierte en:
Inserte la descripción de la imagen aquí

Los números se convierten en cadenas

En el código QML, si encuentra un número en una cadena, puede usar num.toString () para convertir el número en un tipo de cadena

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    
    
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property string testStr: "-100000"
    property int testInt: 44
    property double testDouble: 11.11
    property string testDoubleStr: "22.34432"
    Text {
    
    
        id: intTxt
        text: testStr
        anchors.top: parent.top
        anchors.topMargin: 40
        anchors.left: parent.left
        width: parent.width
        horizontalAlignment: Text.AlignHCenter
        height: 20
    }
    Text {
    
    
        id: doubleTxt
        text: testDoubleStr
        anchors.top: intTxt.bottom
        anchors.left: parent.left
        width: parent.width
        horizontalAlignment: Text.AlignHCenter
        height: 20

    }
    MouseArea {
    
    
        anchors.fill: parent
        onClicked: {
    
    
            testStr = testInt.toString()
            testDoubleStr = testDouble.toString()
        }
    }
}

correr
Inserte la descripción de la imagen aquí

Después de independiente, se convierte en:
Inserte la descripción de la imagen aquí

Artículo de referencia:
[1] Explicación detallada del uso de JavaScript en QML (1) ----- Convertir datos de tipo cadena a datos enteros en qml
[2] Operación de QML en la selección de direcciones, obtener el nombre del archivo, cortar

Supongo que te gusta

Origin blog.csdn.net/PRML_MAN/article/details/113371342
Recomendado
Clasificación