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对地址的操作——选择,获取文件名称,裁剪

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值