Evgenii Legotckoi
Nov. 9, 2015, 3:03 p.m.

QML - Lesson 012. Data transmission from the TextInput in ListView (Model / View)

Working with the ListView in QML is a fairly common aspect in the development of Android applications, since many applications have in their functional building lists of data, records, settings, etc. It is also true in developing a Desktop applications with QML principle would be the same for both platforms.

For its consideration of the transfer of information in the list offer carefully consider the following scenario of interaction with the ListView .

The principle of view data in the ListView

ListView object has two important properties:

  1. delegate - which determines the appearance of a single element ListView
  2. model - which placed the data of each element

The transmission model can be used ListModel object that contains the data for each item in the list. The data assigned to variables that have been assigned to certain properties of the objects in the delegate. In the figure below has two delegate objects Text, text properties which the variables text_first and text_second assigned. These variables determine which will be substituted data from each ListElement in ListModel . As can be seen from the figure, each ListElement has two properties, the name of which is identical to the variables that are assigned to the delegate. In fact, these variables are roles, which put a value of ListModel . So we get ListView with text fields, which are filled with the data that have been made in each ListElement in ListModel .


Work with TextInput

Data will be input into the field TextInput and transmitted into the ListView as a new element. That is, after the data are entered in the TextInput , add a new item in the ListView writing data to it, which are recorded in the TextInput . The event, which will start the transfer of data from the TextInput in the ListView will be pressing the Enter key or click on the special button Button, in which the handler is also added code to add the item to the data of the TextInput in a ListView .

main.qml

  1. import QtQuick 2.5
  2. import QtQuick.Controls 1.4
  3. import QtQuick.Layouts 1.1
  4.  
  5. ApplicationWindow {
  6. visible: true
  7. width: 640
  8. height: 480
  9. title: qsTr("Hello World")
  10.  
  11. RowLayout {
  12. id: rowLayout
  13. anchors.top: parent.top
  14. anchors.left: parent.left
  15. anchors.right: parent.right
  16. anchors.margins: 5
  17. height: 30
  18.  
  19. spacing: 5
  20. z:2 /* location level layers of elements.
  21. * Element with z = 2 is located higher than the element with z = 1
  22. */
  23.  
  24. Rectangle {
  25. Layout.fillWidth: true
  26. Layout.fillHeight: true
  27. color: "white"
  28.  
  29. TextInput {
  30. id: textInput
  31. anchors.fill: parent
  32. horizontalAlignment: Text.AlignHCenter
  33. verticalAlignment: Text.AlignVCenter
  34.  
  35. /* By pressing the Enter key share it with any of the TextInput element in ListView
  36. * */
  37. Keys.onPressed: {
  38. // 16777220 - Enter the key code
  39. if(event.key === 16777220){
  40. listModel.append({ textList: textInput.text })
  41. }
  42. }
  43. }
  44. }
  45.  
  46. /* Button, clicking on which the information is transferred from textInput element in ListView
  47. * */
  48. Button {
  49. id: button
  50. text: qsTr("Add")
  51. Layout.fillHeight: true
  52.  
  53. onClicked: {
  54. listModel.append({ textList: textInput.text })
  55. }
  56. }
  57. }
  58.  
  59. // The list, which is added with the data elements from TextInput
  60. ListView {
  61. id: listView
  62.  
  63. anchors.top: rowLayout.bottom
  64. anchors.left: parent.left
  65. anchors.right: parent.right
  66. anchors.bottom: parent.bottom
  67. anchors.margins: 5
  68. z: 1
  69.  
  70. delegate: Text {
  71. anchors.left: parent.left
  72. anchors.right: parent.right
  73. height: 50
  74. horizontalAlignment: Text.AlignHCenter
  75. verticalAlignment: Text.AlignVCenter
  76.  
  77. text: textList // The role of the property text, which will be transmitted data
  78. }
  79.  
  80. // Model for submission of data in a ListView
  81. model: ListModel {
  82. id: listModel
  83. }
  84. }
  85. }

Conclusion

The algorithm works with a ListView and TextInput valid for other objects instead of TextInput, such as Button, etc.

Retrieving data from objects that are located in ListElement in ListView with buttons similar to the article on dynamic creation and deletion of elements in the ListView.

Video

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup