alex_lip
alex_lipJune 18, 2018, 4:03 a.m.

Qml and JavaScript

Разбираю пример по поводу разницы между qml и javascript

Text {
id: label
x: 24; y: 24
// custom counter property for space presses
property int spacePresses: 0
text: "Space pressed: " + spacePresses + " times"
// (1) handler for text changes
onTextChanged: console.log("text changed to:", text)
// need focus to receive key events
focus: true
// (2) handler with some JS
Keys.onSpacePressed: {
increment()
}
// clear the text on escape
Keys.onEscapePressed: {
label.text = ''
}
// (3) a JS function
function increment() {
spacePresses = spacePresses + 1
}
}


The difference between the QML : (binding) and the JavaScript = (assignment) is, that the binding is a
contract and keeps true over the lifetime of the binding, whereas the JavaScript assignment (=) is a one time value
assignment. The lifetime of a binding ends, when a new binding is set to the property or even when a JavaScript
value is assigned is to the property. For example a key handler setting the text property to an empty string would
destroy our increment display:

Keys.onEscapePressed: {
label.text = ''
}
В принципе понятно, что командой
label.text = ''
мы уничтожили биндинг для label. Но когда я немного подправил

Keys.onEscapePressed: {
label.text = "Space pressed: " + spacePresses + " times"
}
- то есть по сути по ESC я присваиваю полю label - то же самое что и было в text. Однако я не получил того же самого результата. У меня на экране инкремент отображается только по нажатию ESC. То есть биндинг повесился на метод, а не на объект.  Можете пояснить почему?



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
alex_lip
  • June 18, 2018, 4:06 a.m.

и как мне тогда через JS переинициализировать объект в том же виде?

    Александр Панюшкин
    • June 18, 2018, 4:30 a.m.
    • The answer was marked as a solution.

    Можно через states сделать.


        Text {
            id: label
            x: 24; y: 24
            // custom counter property for space presses
            property int spacePresses: 0
            text: "Space pressed: " + spacePresses + " times"
            // (1) handler for text changes
            onTextChanged: console.log("text changed to:", text)
            // need focus to receive key events
            focus: true
            // (2) handler with some JS
            Keys.onSpacePressed: {
            increment()
            }
    
            states: [
                State {
                    name: "onEsc"
                    PropertyChanges {
                        target: label
                        text: ""
                    }
                },
                State {
                    name: "onReleased"
                    PropertyChanges {
                        target: label
                        text: "Space pressed: " + spacePresses + " times"
                    }
                }
            ]
    
            // clear the text on escape
            Keys.onEscapePressed: {
                state = "onEsc"
            }
    
            Keys.onReleased: {
                state = "onReleased"
            }
    
            // (3) a JS function
            function increment() {
            spacePresses = spacePresses + 1
            }
        }
      Александр Панюшкин
      • June 18, 2018, 4:31 a.m.

      По идее, я так думаю, в раздел State{} можно прописать when, к которому привязать кнопки, но я не нашёл, как это правильно сделать.

        alex_lip
        • June 18, 2018, 4:55 a.m.

        Да тут главное принцип понятен. Спасибо. Я теперь понял почему во всех примерах применяют именно state - PropertyChanges .

          Александр Панюшкин
          • June 18, 2018, 4:59 a.m.

          Опять же, ни кто не мешает всё это проделывать непосредственно в JS в Keys.onReleased и Keys.onEscapePressed, но, на сколько я понимаю, чем меньше JS в QML коде, тем лучше. Меньше проблем при отладке большого кол-ва кода возникает. Да и Qt Creator легче ошибки отлавливает.

            alex_lip
            • June 18, 2018, 6:51 a.m.
            В том то и дело что просто в JS так нельзя

            Если использовать state -

            onReleased - не нужен

            вот так все работает


               Text {
                            id: label
                            x: 24; y: 24
                            // custom counter property for space presses
                            property int spacePresses: 0
                            text: "Space pressed: " + spacePresses + " times"
                            // (1) handler for text changes
                            onTextChanged: console.log("text changed to:", text)
                            // need focus to receive key events
                            focus: true
                            // (2) handler with some JS
                            Keys.onSpacePressed: {
                            increment()
                            }
            
                            states: [
                                State {
                                    name: "onEsc"
                                    PropertyChanges {
                                        target: label
                                        text: "Space pressed: " + spacePresses + " times"
                                    }
                                }
                            ]
            
                            // clear the text on escape
                            Keys.onEscapePressed: {
                                state = "onEsc"
                            }
            
                            // (3) a JS function
                            function increment() {
                            spacePresses = spacePresses + 1
                            }
                        }
            Я так понимаю что в этом случае биндинг не слетает

              Comments

              Only authorized users can post comments.
              Please, Log in or Sign up
              e
              • ehot
              • March 31, 2024, 2:29 p.m.

              C++ - Тест 003. Условия и циклы

              • Result:78points,
              • Rating points2
              B

              C++ - Test 002. Constants

              • Result:16points,
              • Rating points-10
              B

              C++ - Test 001. The first program and data types

              • Result:46points,
              • Rating points-6
              Last comments
              k
              kmssrFeb. 8, 2024, 6:43 p.m.
              Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
              Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
              EVA
              EVADec. 25, 2023, 10:30 a.m.
              Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
              J
              JonnyJoDec. 25, 2023, 8:38 a.m.
              Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
              G
              GvozdikDec. 18, 2023, 9:01 p.m.
              Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
              Now discuss on the forum
              a
              a_vlasovApril 14, 2024, 6:41 a.m.
              Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
              Павел Дорофеев
              Павел ДорофеевApril 14, 2024, 2:35 a.m.
              QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
              Mm
              Mind minglesApril 12, 2024, 12:42 a.m.
              ASO Service Forum: Enhancing App Visibility and Reach Welcome to the ASO Service Forum, your ultimate destination for insights, discussions, and strategies revolving around App Store Optimization. ASO (App Store Optimization) is paramoun…
              f
              fastrexApril 4, 2024, 4:47 a.m.
              Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

              Follow us in social networks