如何将用户输入的值存储在变量中?
例如我有这样的代码:
TextField {width: 37; height: 19
var
id: q1
x: 91
y: 29
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.centerIn: parent
placeholderText: "0"
font.pixelSize: 12
text: ""
anchors.verticalCenterOffset: 26
anchors.horizontalCenterOffset: -115
validator: IntValidator{}
horizontalAlignment: TextInput.AlignHCenter
style: TextFieldStyle {
textColor: "black"
background: Rectangle { width: 45; height: 25; radius: 20.0
color: "#F0EBEB"
implicitWidth: 40
implicitHeight: 24
border.color: "#000000"
border.width: 1
}
}
onTextChanged: {console.log(parseInt(text,10) + 1000)}
}
我可以稍后使用该 id 进行求和或乘法运算吗?如果可以,那么怎么做?
答案1
您可以在 TextField 组件之外重复使用文本属性。
请看以下示例,其中 Text 元素显示输入文本 + 5 的结果:
对应代码:
import QtQuick 2.0
import Ubuntu.Components 0.1
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
MainView {
id: main
width: 300
height: 150
Row {
width: 37;
height: 19
spacing: units.gu(3)
TextField {
id: q1
placeholderText: "0"
font.pixelSize: 12
text: "0"
validator: IntValidator{}
horizontalAlignment: TextInput.AlignHCenter
style: TextFieldStyle {
textColor: "black"
background: Rectangle {
width: 45;
height: 25;
radius: 20.0
color: "#F0EBEB"
implicitWidth: 40
implicitHeight: 24
border.color: "#000000"
border.width: 1
}
}
}
Text {
height: 25;
text: "TextField + 5 = "+(parseInt(q1.text, 10) + 5)
}
}
}
更新:
要全局存储两个文本输入的总和,您可以在父元素中定义一个属性,看以下代码:
import QtQuick 2.0
import Ubuntu.Components 0.1
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
MainView {
id: main
width: 300
height: 300
property var sum_q1_q2: parseInt(q1.text, 10) + parseInt(q2.text, 10)
Column {
width: 37;
height: 19
spacing: units.gu(3)
TextField {
id: q1
placeholderText: "0"
font.pixelSize: 12
text: "0"
validator: IntValidator{}
horizontalAlignment: TextInput.AlignHCenter
style: TextFieldStyle {
textColor: "black"
background: Rectangle {
width: 45;
height: 25;
radius: 20.0
color: "#F0EBEB"
implicitWidth: 40
implicitHeight: 24
border.color: "#000000"
border.width: 1
}
}
}
TextField {
id: q2
placeholderText: "0"
font.pixelSize: 12
text: "0"
validator: IntValidator{}
horizontalAlignment: TextInput.AlignHCenter
style: TextFieldStyle {
textColor: "black"
background: Rectangle {
width: 45;
height: 25;
radius: 20.0
color: "#F0EBEB"
implicitWidth: 40
implicitHeight: 24
border.color: "#000000"
border.width: 1
}
}
}
Text {
height: 25;
text: "Q1 + Q2 = "+main.sum_q1_q2
}
}
}
新的文本元素现在使用“主要”组件的属性: