Russian Qt Forum
Март 28, 2024, 17:26
Добро пожаловать,
Гость
. Пожалуйста,
войдите
или
зарегистрируйтесь
.
Вам не пришло
письмо с кодом активации?
1 час
1 день
1 неделя
1 месяц
Навсегда
Войти
Начало
Форум
WIKI (Вики)
FAQ
Помощь
Поиск
Войти
Регистрация
Russian Qt Forum
>
Forum
>
Qt
>
Qt Quick
(Модератор:
navrocky
) >
QML DATAEDIT
Страниц: [
1
]
Вниз
« предыдущая тема
следующая тема »
Печать
Автор
Тема: QML DATAEDIT (Прочитано 6629 раз)
Rphoenix
Новичок
Offline
Сообщений: 10
QML DATAEDIT
«
:
Июнь 20, 2020, 22:53 »
Здравствуйте, какой элемент QML можно использовать под редактирование даты? Мне нужен простой Edit, чтобы пользователь ввел 21052020 и ему автоматический точки расставились, т.е. стало 21.05.2020 и дальше не позволяло вводить. Я так понимаю, что это самому через функции нужно?
Функцию получении даты сделал.
function addZero(value){
if(value<10){
return '0' + value
}
else{
return value
}
}
function getFormat(date){
var year = date.getFullYear()
var month = date.getMonth()
var day = date.getDate()
return addZero(day) + '.' + addZero(month+1) + '.' + year
}
Записан
Rphoenix
Новичок
Offline
Сообщений: 10
Re: QML DATAEDIT
«
Ответ #1 :
Июнь 21, 2020, 02:25 »
Сделал элемент, все вводится. Осталось только проверить дату на корректность. Как быть? Есть метод isValid, но он почему-то работать не хочет.
Код:
import QtQuick 2.0
import QtQuick.Controls 1.4
Item {
id: dateEdit
readonly property date currentDate: calendar.selectedDate
readonly property bool isCalendarOpened: calendar.visible
property string color: "lightblue"
signal calendarOpened;
signal calendarClosed;
width: textField.width + btnOpen.width
height: textField.height
Column {
id: column
spacing: 2
Row {
spacing: 5
TextField {
id: textField
text: Qt.formatDate(calendar.selectedDate, "dd.MM.yyyy");
// readOnly: true
Keys.onPressed:
{
if (text.isValid()) {
console.log ( "Date " + " is a valid date")
} else {
console.log ("Date " + " is not a valid date")
}
console.log("Press = " + event.key)
console.log("Current text is " + text)
}
Keys.onReleased:
{ text: "99.99.9999"
console.log("Release = " + event.key)
console.log("Current text is " + text)
}
inputMask: "99.99.9999"
inputMethodHints: Qt.ImhDigitsOnly
Keys.onUpPressed: calendar.__selectNextDay()
Keys.onDownPressed: calendar.__selectPreviousDay()
}
Rectangle {
id: btnOpen
radius: 5
width: 30
height: textField.height
color: dateEdit.color
Text {
text: "*"
}
MouseArea {
anchors.fill: parent
onClicked: {
dateEdit.isCalendarOpened ? closeCalendar() : openCalendar()
}
}
}
}
Calendar {
id: calendar
visible: false
dayOfWeekFormat: Locale.ShortFormat
onClicked: {
closeCalendar()
}
function open()
{
visible = true
}
function close()
{
visible = false
}
}
}
function openCalendar()
{
calendar.open()
calendarOpened()
}
function closeCalendar()
{
calendar.close()
calendarClosed()
}
}
Записан
Rphoenix
Новичок
Offline
Сообщений: 10
Re: QML DATAEDIT
«
Ответ #2 :
Июнь 21, 2020, 08:31 »
Доделал, но остался единственный баг с месяцами: число он нормально отрабатывает, а если ввожу месяц и стоит 06, то получается 16, то он сбрасывается. Как исправить?
Код:
import QtQuick 2.0
import QtQuick.Controls 1.4
Item {
id: dateEdit
readonly property date currentDate: calendar.selectedDate
readonly property bool isCalendarOpened: calendar.visible
property string color: "lightblue"
signal calendarOpened;
signal calendarClosed;
width: textField.width + btnOpen.width
height: textField.height
Column {
id: column
spacing: 2
Row {
spacing: 5
TextField {
id: textField
text: Qt.formatDate(calendar.selectedDate, "dd.MM.yyyy");
// readOnly: true
function validate_date(value)
{
var arrD = value.split(".");
arrD[1] -= 1;
var d = new Date(arrD[2], arrD[1], arrD[0]);
if ((d.getFullYear() == arrD[2]) && (d.getMonth() == arrD[1]) && (d.getDate() == arrD[0])) {
return true;
} else {
return false;
}
}
function getMonth(value)
{
var arrm = value.split(".");
arrm[1] -= 0;
return arrm[1];
}
function getDay(value)
{
var arrd = value.split(".");
arrd[0] -= 0;
return arrd[0];
}
Keys.onReleased:
{validate_date(text)?console.log("Current data: "+(text.substring(3,5))):{text=Qt.formatDate(calendar.selectedDate, "dd.MM.yyyy")}}
inputMask: "99.99.9999"
inputMethodHints: Qt.ImhDigitsOnly
Keys.onUpPressed: calendar.__selectNextDay()
Keys.onDownPressed: calendar.__selectPreviousDay()
}
Rectangle {
id: btnOpen
radius: 5
width: 30
height: textField.height
color: dateEdit.color
Text {
text: "*"
}
MouseArea {
anchors.fill: parent
onClicked: {
dateEdit.isCalendarOpened ? closeCalendar() : openCalendar()
}
}
}
}
Calendar {
id: calendar
visible: false
dayOfWeekFormat: Locale.ShortFormat
onClicked: {
closeCalendar()
}
function open()
{
visible = true
}
function close()
{
visible = false
}
}
}
function openCalendar()
{
calendar.open()
calendarOpened()
}
function closeCalendar()
{
calendar.close()
calendarClosed()
}
}
«
Последнее редактирование: Июнь 21, 2020, 10:15 от Rphoenix
»
Записан
Rphoenix
Новичок
Offline
Сообщений: 10
Re: QML DATAEDIT
«
Ответ #3 :
Июнь 22, 2020, 21:11 »
Доделал
Код:
import QtQuick 2.0
import QtQuick.Controls 1.4
Item {
id: dateEdit
readonly property date currentDate: calendar.selectedDate
readonly property bool isCalendarOpened: calendar.visible
property string color: "lightblue"
signal calendarOpened;
signal calendarClosed;
width: textFielddata.width + btnOpen.width
height: textFielddata.height
Column {
id: column
spacing: 2
Row {
spacing: 5
TextField {
id: textFielddata
text: Qt.formatDate(calendar.selectedDate, "dd.MM.yyyy");
// readOnly: true
function validate_date(value)
{
var arrD = value.split(".");
arrD[1] -= 1;
var d = new Date(arrD[2], arrD[1], arrD[0]);
if ((d.getFullYear() == arrD[2]) && (d.getMonth() == arrD[1]) && (d.getDate() == arrD[0])) {
return true;
} else {
return false;
}
}
validator: RegExpValidator { regExp: /^([0-2]?[1-9]|3[0-9]).(0?[1-9]|1[0-9]).([0-9][0-9][0-9][0-9])$ / } // /^([0-2]?[1-9]|3[0-1]).(0?[1-9]|1[0-2]).([0-9][0-9][0-9][0-9])$ /
Keys.onReleased:
{if (validate_date(text)) {console.log("Current data: "+(text))} else if ([text[3]].toString() == "1") {text=text.substring(0,4)+0+text.substring(5);textFielddata.cursorPosition=5} else if ([text[0]].toString() == "3"&&([text[1]].toString()!="0")&&([text[1]].toString()!="1")) {text=text.substring(0,1)+0+text.substring(2);textFielddata.cursorPosition=1} else {text="01"+text.substring(2);textFielddata.cursorPosition=0}}
inputMask:"99.99.9999";
inputMethodHints: Qt.ImhDigitsOnly
Keys.onUpPressed: calendar.__selectNextDay()
Keys.onDownPressed: calendar.__selectPreviousDay()
}
Rectangle {
id: btnOpen
radius: 5
width: 30
height: textFielddata.height
color: dateEdit.color
Text {
text: "*"
}
MouseArea {
anchors.fill: parent
onClicked: {
dateEdit.isCalendarOpened ? closeCalendar() : openCalendar()
}
}
}
}
Calendar {
id: calendar
visible: false
dayOfWeekFormat: Locale.ShortFormat
onClicked: {
closeCalendar()
}
function open()
{
function get_date(value)
{
var arrD = value.split(".");
arrD[1] -= 1;
var d = new Date(arrD[2], arrD[1], arrD[0]);
if ((d.getFullYear() == arrD[2]) && (d.getMonth() == arrD[1]) && (d.getDate() == arrD[0])) {
return d;
} else {
return false;
}}
calendar.selectedDate=new Date(get_date(textFielddata.text));
visible = true
}
function close()
{
visible = false
}
}
}
function open()
{
function get_date(value)
{
var arrD = value.split(".");
arrD[1] -= 1;
var d = new Date(arrD[2], arrD[1], arrD[0]);
if ((d.getFullYear() == arrD[2]) && (d.getMonth() == arrD[1]) && (d.getDate() == arrD[0])) {
return d;
} else {
return false;
}}
calendar.selectedDate=new Date(get_date(textFielddata.text));
visible = true
}
function closeCalendar()
{
calendar.close()
calendarClosed()
}
}
Вызов
Код:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.5
import QtQuick.Controls 2.5
Window {
visible: true
width: 640
height: 480
title: qsTr("QML DATAEDIT тест")
QmlDateEdit{
}
}
«
Последнее редактирование: Июнь 27, 2020, 16:24 от Rphoenix
»
Записан
navrocky
Moderator
Гипер активный житель
Offline
Сообщений: 817
Погроммист
Re: QML DATAEDIT
«
Ответ #4 :
Июль 13, 2020, 20:47 »
Боюсь Вас огорчить, но уже есть встроенный ввод по маске:
https://doc.qt.io/qt-5/qml-qtquick-textinput.html#inputMask-prop
Код:
0000-00-00
ISO Date; blanks are space
«
Последнее редактирование: Июль 13, 2020, 20:49 от navrocky
»
Записан
Гугль в помощь
Страниц: [
1
]
Вверх
Печать
« предыдущая тема
следующая тема »
Перейти в:
Пожалуйста, выберите назначение:
-----------------------------
Qt
-----------------------------
=> Вопросы новичков
=> Уроки и статьи
=> Установка, сборка, отладка, тестирование
=> Общие вопросы
=> Пользовательский интерфейс (GUI)
=> Qt Quick
=> Model-View (MV)
=> Базы данных
=> Работа с сетью
=> Многопоточное программирование, процессы
=> Мультимедиа
=> 2D и 3D графика
=> OpenGL
=> Печать
=> Интернационализация, локализация
=> QSS
=> XML
=> Qt Script, QtWebKit
=> ActiveX
=> Qt Embedded
=> Дополнительные компоненты
=> Кладовая готовых решений
=> Вклад сообщества в Qt
=> Qt-инструментарий
-----------------------------
Программирование
-----------------------------
=> Общий
=> С/C++
=> Python
=> Алгоритмы
=> Базы данных
=> Разработка игр
-----------------------------
Компиляторы и платформы
-----------------------------
=> Linux
=> Windows
=> Mac OS X
=> Компиляторы
===> Visual C++
-----------------------------
Разное
-----------------------------
=> Новости
===> Новости Qt сообщества
===> Новости IT сферы
=> Говорилка
=> Юмор
=> Объявления
Загружается...