АЧ
Маусым 24, 2016, 11:29 Т.Қ.

Списки на QML

список, qml, Qt, список на QML

Всем привет. Как сделать сохранение моих данных в таблице с помощью динамических списков и реализовать удаление выбранной строки? Исходники прикрепил. Имеется код файла
main.qml

import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick 2.5
import QtQuick.Layouts 1.1
import QtQuick.Dialogs 1.2
 
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.LocalStorage 2.0
 
ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Таблица товаров")
 
    // Слой в котором располагается TextInput и Button
    RowLayout {
        id: rowLayout
        anchors.top: parent.top
        width: 150
 
        anchors.margins: 5
        height: 30
 
        spacing: 5
        z:2         /* Уровень расположения слоёв элементов.
                     * Элемент с z = 2 располагается выше, чем элемент с z = 1
                     */
 
        // Область с TextInput
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
 
            TextInput {
                id: textInput
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
 
 
                /* По нажатию клавиши Enter передаём информацию
                 * из TextInput в элемент ListView
                 * */
                Keys.onPressed: {
                    // 16777220 - код клавиши Enter
                    if(event.key === 16777220){
                        listModel.append({ textList: textInput.text })
                    }
                }
            }
        }
 
        /* Кнопка, по нажатию которой передаётся информация из
         * textInput в элемент ListView
         * */
 
    }
    RowLayout {
        id: rowLayout2
        anchors.top: parent.top
        width: 65
        x:160
 
        anchors.margins: 5
        height: 30
 
        spacing: 5
        z:2         /* Уровень расположения слоёв элементов.
                     * Элемент с z = 2 располагается выше, чем элемент с z = 1
                     */
 
        // Область с TextInput
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
 
            TextInput {
 
                id: textInput2
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
 
                /* По нажатию клавиши Enter передаём информацию
                 * из TextInput в элемент ListView
                 * */
                Keys.onPressed: {
                    // 16777220 - код клавиши Enter
                    if(event.key === 16777220){
                        listModel2.append({ textList2: textInput2.text })
                    }
                }
            }
        }
    }
    RowLayout {
        id: rowLayout3
        anchors.top: parent.top
        width: 65
        x:230
 
        anchors.margins: 5
        height: 30
 
        spacing: 5
        z:2         /* Уровень расположения слоёв элементов.
                     * Элемент с z = 2 располагается выше, чем элемент с z = 1
                     */
 
 
 
        // Область с TextInput
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
 
            TextInput {
 
                id: textInput3
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
 
 
                /* По нажатию клавиши Enter передаём информацию
                 * из TextInput в элемент ListView
                 * */
                Keys.onPressed: {
                    // 16777220 - код клавиши Enter
                    if(event.key === 16777220){
                        listModel3.append({ textList3: textInput3.text })
                    }
                }
            }
        }
    }
 
    // Список, в который добавляются элементы с данными из TextInput
    TableView {
 
        id: listView
 
        anchors.top: rowLayout.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 5
        z: 1 // Расположение ниже, чем слой с TextInput и Button
        rowDelegate: Rectangle {
            anchors.fill: parent
            color: styleData.selected ? 'skyblue' : (styleData.alternate ? 'whitesmoke' : 'white');
            MouseArea {
                anchors.fill: parent
                acceptedButtons: Qt.RightButton | Qt.LeftButton
                onClicked: {
                    tableView.selection.clear()
                    tableView.selection.select(styleData.row)
                    tableView.currentRow = styleData.row
                    tableView.focus = true
 
                    switch(mouse.button) {
                    case Qt.RightButton:
                        contextMenu.popup() // Вызываем контексткное меню
                        break
                    default:
                        break
                    }
                }
            }
        }
 
        TableViewColumn {
 
 
            role: "Name_product"
            title: "Наименование товара"
 
 
        }
 
        // Описание внешнего вида одного элемента в ListView
          Text {
 
 
            text: textList // Роль свойства text, в которую будут передаваться данные
 
 
        }
 
 
        // Модель для представления данных в ListView
        model: ListModel {
            id: listModel
        }
    }
    TableView {
 
        id: listView2
 
        anchors.top: rowLayout.bottom
        x:150
        width:80
        //anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 5
        z: 1 // Расположение ниже, чем слой с TextInput и Button
 
        TableViewColumn {
 
 
            role: "Name_product"
            title: "Поступило"
 
 
        }
 
        // Описание внешнего вида одного элемента в ListView
          Text {
 
 
            text: textList2 // Роль свойства text, в которую будут передаваться данные
 
        }
 
 
        // Модель для представления данных в ListView
        model: ListModel {
            id: listModel2
        }
    }
    TableView {
 
        id: listView3
 
        anchors.top: rowLayout.bottom
        x:230
        width:70
        //anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 5
        z: 1 // Расположение ниже, чем слой с TextInput и Button
 
 
        TableViewColumn {
 
 
            role: "Name_product"
            title: "Убыло"
 
 
        }
 
        // Описание внешнего вида одного элемента в ListView
          Text {
 
 
            text: textList3 // Роль свойства text, в которую будут передаваться данные
 
        }
 
 
        // Модель для представления данных в ListView
        model: ListModel {
            id: listModel3
        }
    }
    RowLayout {
        id: rowLayout4
        anchors.top: parent.top
        width: 65
        x:400
 
        anchors.margins: 5
        height: 30
 
        spacing: 5
        z:2
 
        /* Уровень расположения слоёв элементов.
                     * Элемент с z = 2 располагается выше, чем элемент с z = 1
                     */
        Button {
            id: button
            text: qsTr("добавить")
            Layout.fillHeight: true
 
            onClicked: {
                listModel.append({ textList: textInput.text })
                listModel3.append({ textList3: textInput3.text })
                listModel2.append({ textList3: textInput2.text })
            }
        }
 
 
        // Область с TextInput
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
 
 
        }
    }
 
    RowLayout {
        id: rowLayout5
        anchors.top: parent.top
        width: 65
        x:500
 
        anchors.margins: 5
        height: 30
 
        spacing: 5
        z:2
 
        /* Уровень расположения слоёв элементов.
                     * Элемент с z = 2 располагается выше, чем элемент с z = 1
                     */
        Button {
            id: button2
            text: qsTr("удалить")
            Layout.fillHeight: true
 
            onClicked: {
                listModel.remove({ textList: textInput.text })
                listModel3.remove({ textList3: textInput3.text })
                listModel2.remove({ textList2: textInput2.text })
 
            }
        }
 
 
        // Область с TextInput
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
 
 
        }
    }
   
   
 
}

proba_spiskov.rar

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

3
Evgenii Legotckoi
  • Маусым 25, 2016, 10:22 Т.Ж.

Добрый день

Как сделать сохранение моих данных в таблице с помощью динамических списков и реализовать удаление выбранной строки?

Я правильно понимаю, что речь идёт о сохранении динамического списка в базе данных?
Судя по некоторым импортам в main.qml, так оно и есть.
Я больше предпочитаю бизнес-логику выносить в слой C++.
Гляньте для начала вот эту статью по работе с базой данных SQLite в QML Возможно, это натолкнёт Вас на нужное решение.

    АЧ
    • Маусым 25, 2016, 5:55 Т.Қ.
    Нет, нужно данные сохранить в двоичных файлах и при обработке использовать динамические списки. Так думаю более подробно
      АЧ
      • Маусым 26, 2016, 12:35 Т.Ж.
      • Жауап шешім ретінде белгіленді.

      Вопрос решен с применением базы данных. Кому интересно, можете поюзать проект:) Отдельное спасибо Евгению за помощь)))
      Вход под админом Логин:1, пароль:1
      Вход под диспетчером Логин:22, пароль:2
      Вход под рабочим Логин:33, пароль:33

      qmldatabase.rar

        Пікірлер

        Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
        Кіріңіз немесе Тіркеліңіз