АЧ
Алексей ЧепрасовJune 24, 2016, 1:29 p.m.

Списки на 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

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!

3
Evgenii Legotckoi
  • June 25, 2016, 12:22 a.m.

Добрый день

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

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

    Нет, нужно данные сохранить в двоичных файлах и при обработке использовать динамические списки. Так думаю более подробно
      АЧ
      • June 25, 2016, 2:35 p.m.
      • The answer was marked as a solution.

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

      qmldatabase.rar

        Comments

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

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

        • Result:33points,
        • Rating points-10
        г
        • ги
        • April 23, 2024, 3:51 p.m.

        C++ - Test 005. Structures and Classes

        • Result:41points,
        • Rating points-8
        l
        • laei
        • April 23, 2024, 9:19 a.m.

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

        • Result:10points,
        • Rating points-10
        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
        G
        GarApril 22, 2024, 5:46 a.m.
        Clipboard Как скопировать окно целиком в clipb?
        DA
        Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
        Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
        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 с многорядностью проект поддерживается, обращайтесь
        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