QML String and number conversion

String converted to number

In QML code, if you encounter a string to a number, you can use Number (str) to convert str to a number type

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)
        }
    }
}

After running the
Insert picture description here
stand-alone machine, it becomes:
Insert picture description here

Numbers are converted to strings

In QML code, if you encounter a number to a string, you can use num.toString() to convert the number to a string type

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()
        }
    }
}

run
Insert picture description here

After stand-alone, it becomes:
Insert picture description here

Reference articles:
[1] Detailed explanation of JavaScript usage in QML (1) ----- Convert string type data to integer data in qml
[2] QML's operation on address-select, get file name, cut

Guess you like

Origin blog.csdn.net/PRML_MAN/article/details/113371342