РС
Руслан СклюевJune 20, 2020, 3:55 p.m.

QML DATAEDIT

Здравствуйте, какой элемент 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
    }
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

6
РС
  • June 20, 2020, 7:26 p.m.

Сделал элемент, все вводится. Осталось только проверить дату на корректность. Как быть? Есть метод 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()
    }
}

    РС
    • June 21, 2020, 1:32 a.m.
    • (edited)

    Доделал, но остался единственный баг с месяцами: число он нормально отрабатывает, а если ввожу месяц и стоит 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()
        }
    }
    
      S
      • June 21, 2020, 6:54 a.m.
      • (edited)

      Либо, это не полный код, либо... Просто непонятно откуда взялся массив arrm в функции getMounth , так как вы используете arrd

        РС
        • June 21, 2020, 6:56 a.m.

        там несколько функций

          РС
          • June 22, 2020, 2:15 p.m.

          Доделал

          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 openCalendar()
              {
                  calendar.open()
                  calendarOpened()
              }
          
              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{
          
              }
          
          }
          
          
            РС
            • June 27, 2020, 9:23 a.m.
            • (edited)

            Доработка функции:

            Доработка функции:
            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
            
                        }
            

              Comments

              Only authorized users can post comments.
              Please, Log in or Sign up
              AD

              C ++ - Test 004. Pointers, Arrays and Loops

              • Result:50points,
              • Rating points-4
              m

              C ++ - Test 004. Pointers, Arrays and Loops

              • Result:80points,
              • Rating points4
              m

              C ++ - Test 004. Pointers, Arrays and Loops

              • Result:20points,
              • Rating points-10
              Last comments
              i
              innorwallNov. 14, 2024, 12:07 p.m.
              Circuit switching and packet data transmission networks Angioedema 1 priligy dapoxetine
              i
              innorwallNov. 14, 2024, 11:42 a.m.
              How to Copy Files in Linux If only females relatives with DZ offspring were considered these percentages were 23 order priligy online uk
              i
              innorwallNov. 14, 2024, 9:09 a.m.
              Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
              i
              innorwallNov. 14, 2024, 4:05 a.m.
              EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
              i
              innorwallNov. 14, 2024, 4 a.m.
              PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
              Now discuss on the forum
              i
              innorwallNov. 14, 2024, 3:39 a.m.
              добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
              i
              innorwallNov. 11, 2024, 10:55 a.m.
              Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
              9
              9AnonimOct. 25, 2024, 9:10 a.m.
              Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

              Follow us in social networks