QML String和数字互相转换

String 转换成数字

QML代码中,如果遇到字符串转数字,可以使用Number(str)将str转换成数字类型

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

运行
在这里插入图片描述
单机后变成:
在这里插入图片描述

数字转换成字符串

QML代码中,如果遇到数字转字符串,可以使用num.toString()将数字转换成字符串类型

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

运行
在这里插入图片描述

单机后变成:
在这里插入图片描述

参考文章:
[1]QML中的JavaScript用法详解(一)-----在qml中将字符串类型数据转换为整型数据
[2]QML对地址的操作——选择,获取文件名称,裁剪

猜你喜欢

转载自blog.csdn.net/PRML_MAN/article/details/113371342
QML
今日推荐