Диалог смены пароля на QML
Article Metadata
Tested with
SDK: Nokia Qt SDK 1.2
Devices(s): все устройства на базе Symbian Anna, Nokia Belle
Compatibility
Platform(s): Symbian Anna, Nokia Belle
Device(s): All
Dependencies: Symbian Qt Quick Components 1.1
Platform Security
Capabilities: None
Article
Keywords: Qml, пароль, диалог
Translated:
By Den123
Last edited: Den123
(25 Mar 2012)
Стандартные компоненты, входящие в состав QML Components для Symbian OS, не содержат такого часто используемого диалога, как диалог смены пароля. Ниже приведен код QML-компонента, реализующего указанную функциональность.
Ниже представлен код QML-компонента, реализующего данную функциональность.
Компонент использует CommonDialog в качестве основы и предлагает следующие настройки:
- showClearPassword - не маскировать вводимый пароль и подтверждение
- minNumberOfCharacters - минимально возможное кол-во символов в пароле (если указан 0, то пользователь может задать пустой пароль)
- function advancedCheck( pwd ) - функция позволяет задать дополнительные проверки пароля. Данная функция должна возвращать пустую строку если проверка прошла успешно, иначе сообщение об ошибке.
Для вывода предупреждений ("Password cannot be empty!", "Password does not match confirm!", сообщение об ошибке advancedCheck ) используется отдельный компонент hintArea. Появление и скрытие hintArea выполнено с использованием анимации.
Исходный код
ChangePasswordDialog.qml:
import QtQuick 1.1
import com.nokia.symbian 1.1
CommonDialog {
id: root
privateCloseIcon: true // show close button in the right corner of dialogs title
titleText: qsTr( "Set Password" )
property alias edPasswordPlaceholderText: edPassword.placeholderText
property alias edConfirmPlaceholderText: edPasswordConfirm.placeholderText
property string password: ""
property bool showClearPassword: false
property int minNumberOfCharacters: 6
property string msgMinNumberOfCharacters: qsTr( "Minimum number of characters: " )
property string msgPasswordDoesNotMatchConfirm: qsTr( "Password does not match confirm!" )
function advancedCheck( pwd )
{
// this function may contain additional password check
// if something wrong - function should return error message,
// otherwise function should return empty string
return ""
}
function launch() {
password = ""
edPassword.text = ""
edPasswordConfirm.text = ""
open()
}
// we want to use only one button with own onClicked handler
buttons: Item {
id: buttonContainer
LayoutMirroring.enabled: false
LayoutMirroring.childrenInherit: true
width: parent.width
height: privateStyle.toolBarHeightLandscape + platformStyle.paddingSmall * 2
Row {
id: buttonRow
objectName: "buttonRow"
anchors.centerIn: parent
spacing: platformStyle.paddingMedium
ToolButton {
id: btOk
text: qsTr( "Ok" )
onClicked: {
// check password and confirmation
hintArea.state = "Hide"
if( edPassword.text != edPasswordConfirm.text )
showHint( msgPasswordDoesNotMatchConfirm )
else {
if( edPassword.text.length < minNumberOfCharacters )
showHint( msgMinNumberOfCharacters + minNumberOfCharacters )
else
{
var msg = advancedCheck( edPassword.text )
if( msg.length !== 0 )
showHint( msg )
else
{
password = edPassword.text
accept();
}
}
}
}
}
}
}
content: Item {
id: content
height: edPassword.height * 2 + column.spacing * 2 + hintArea.height +
column.anchors.topMargin + column.anchors.bottomMargin
width: parent.width
anchors.top: parent.top
Column {
id: column
spacing: platformStyle.paddingMedium
anchors.fill: parent
anchors {
leftMargin: platformStyle.borderSizeMedium
rightMargin: platformStyle.borderSizeMedium
topMargin: platformStyle.borderSizeMedium
}
TextField {
id: edPassword
anchors.left: parent.left
anchors.right: parent.right
echoMode: showClearPassword ? TextInput.Normal : TextInput.Password
placeholderText: qsTr( "Enter password" )
onTextChanged: hintArea.state = "Hide"
}
TextField {
id: edPasswordConfirm
anchors.left: parent.left
anchors.right: parent.right
echoMode: showClearPassword ? TextInput.Normal : TextInput.Password
placeholderText: qsTr( "Confirm password" )
onTextChanged: hintArea.state = "Hide"
}
Item {
id: hintArea
state: "Hide"
anchors.left: parent.left
anchors.right: parent.right
property alias text: hintText.text
states: [
State {
name: "Show"
PropertyChanges { target: hintArea; height: hintText.paintedHeight }
},
State {
name: "Hide"
PropertyChanges { target: hintArea; height: 1 }
}
]
// add hide-show animation
transitions: [
Transition {
from: "Hide"; to: "Show"
NumberAnimation { target: hintArea; properties: "height"; duration: 300; easing.type: Easing.OutQuad }
},
Transition {
from: "Show"; to: "Hide"
NumberAnimation { target: hintArea; properties: "height"; duration: 300; easing.type: Easing.OutQuad }
}
]
Text {
id: hintText
anchors.fill: parent
anchors.margins: 1
horizontalAlignment: Text.AlignHCenter
color: platformStyle.colorHighlighted
wrapMode: Text.WordWrap
text: ""
}
}
}
}
function showHint( msg )
{
hintArea.text = msg
hintArea.state = "Show"
}
}
Как использовать:
ToolButton {
anchors.centerIn: parent
text: qsTr("Set password")
onClicked: dlg.launch();
}
ChangePasswordDialog {
id: dlg
minNumberOfCharacters: 3
onAccepted: console.log( "New password: " + dlg.password )
onRejected: console.log( "Password not defined" )
function advancedCheck( pwd )
{
// just for fun
return pwd === "123" ? qsTr( "Password is too simple!" ) : ""
}
}



(no comments yet)