开发环境: Window10 Qt5.13.1
在qml中,有的输入框的内容是有固定格式的,比如:经度-180.0~180.0之间,纬度-90.0~90.0之间,因此在设置输入框的输入内容时,就得限制这种格式,需要什么样的规则才能设定这些格式呢,正则表达式可以满足这些需求,
下面以TextField输入框的使用为例,代码如下:
import QtQuick 2.13
import QtQuick.Controls 2.12
Rectangle {
id: homeRect
color: "#373250"//"green"
property int textWidth: 220
property int textHeigh: 36
property string longitude: "113.267532"//经度 广州坐标
property string latitude: "23.137965"//纬度
//经度Text
Text {
id: longitudeText
width: 50; height: textHeigh
color: "#FFA109"
font.pixelSize: 14
font.family: strFontFamily
text: qsTr("经度:")//qsTr("longitude:")
anchors{top: parent.top; topMargin: 100; left: parent.left; leftMargin: 180}
horizontalAlignment: Text.AlignLeft//水平左对齐
verticalAlignment: Text.AlignVCenter//垂直居中
}
//经度TextField
TextField {
id: longitudeTextField
focus: true
anchors.top: parent.top; anchors.topMargin: 100
anchors.left: parent.left; anchors.leftMargin: 220
verticalAlignment: Text.AlignVCenter
font.pixelSize: 14
color: (longitudeTextField.text.length > 0) ? "#333333" : "#999999"
cursorVisible: true
selectByMouse: true
selectionColor: "#999999"
placeholderText: qsTr("请输入经度,例如:113.267532")
validator: RegExpValidator{regExp: (/^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/)}
width: textWidth; height: textHeigh
background: Rectangle {
border.width: 0
radius: 4
implicitHeight: textHeigh
implicitWidth: textWidth
}
}
//纬度Text
Text {
id: latitudeText
width: 50; height: textHeigh
color: "#FFA109"
font.pixelSize: 14
font.family: strFontFamily
text: qsTr("纬度:")//latitude
//ToolTip.text: qsTr("纬度:")
//ToolTip.visible: true
anchors{top: parent.top; topMargin: 180; left: parent.left; leftMargin: 180}
horizontalAlignment: Text.AlignLeft//水平左对齐
verticalAlignment: Text.AlignVCenter//垂直居中
}
//纬度TextField
TextField {
id: latitudeTextField
focus: true
anchors.top: parent.top; anchors.topMargin: 180
anchors.left: parent.left; anchors.leftMargin: 220
verticalAlignment: Text.AlignVCenter
font.pixelSize: 14
color: (latitudeTextField.text.length > 0) ? "#333333" : "#999999"
cursorVisible: true
selectByMouse: true
selectionColor: "#999999"
placeholderText: qsTr("请输入纬度,例如:23.137965")
validator: RegExpValidator{regExp: (/^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/)}
width: textWidth; height: textHeigh
background: Rectangle {
border.width: 0
radius: 4
implicitHeight: textHeigh
implicitWidth: textWidth
}
}
}