Виталий Антипов
Виталий АнтиповDec. 21, 2016, 7:21 a.m.

Удаление записи из БД (Qml ListView)

ListView, QML

На основе урока “База данных SQLite и работа с ней в QML Qt” делаю проект с представлением данных в ListView. Уперся в удалении записи из списка, точнее в получении индекса(Id) выбранного элемента. При выборе (подсветке) элемента кликом мыши значение view.currentIndex соответствует выбранному, но при передаче в getId удаляется всегда первый элемент. В чем моя ошибка? Поправьте пожалуйста.

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
Item {
    id: item1    
    RowLayout {
        anchors.fill: parent
        Rectangle {
            id: rec1
            z:1
            anchors.left: parent.left            
            anchors.top: parent.top            
            height: item1.height
            width: 300
            color: "white"
            border.width: 2
            border.color: "#353637"
            Row{
                id: row1
                anchors.left: rec1.left
                anchors.leftMargin: 5
                anchors.right: rec1.right
                anchors.rightMargin: 5
                anchors.top: rec1.top
                anchors.topMargin: 5
                height: 40
                spacing: 5
                TextField {
                    id: tf1
                    width: 200
                    placeholderText: "Идентификатор"
                    font.pixelSize: 20
                }
                Button {
                    width: rec1.width - tf1.width - 15
                    highlighted: true
                    Text {
                        id: name1
                        text: qsTr("Поиск")
                        font.family: "Arial"
                        font.bold: true
                        color: "white"
                        font.pixelSize: 20
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
            }
            /* Область списка */
            Rectangle {
                id: rec2
                color: "white"
                border.width: 1
                border.color: "#353637"
                width: rec1.width - 10
                anchors.left: rec1.left
                anchors.leftMargin: 5
                anchors.top: row1.bottom
                anchors.topMargin: 5
                anchors.bottom: row2.top
                anchors.bottomMargin: 5
                Flickable {
                    id: view
                    width: list.width
                    anchors.fill: parent
                    contentWidth: list.width
                    ListView {
                        id: list
                        width: rec2.width
                        height: rec2.height
                        anchors.fill: parent
                        model: QueryModel1
                        delegate: numberDelegate
                        focus: true
                        headerPositioning: ListView.OverlayHeader
                        spacing: 1
                        highlight: Rectangle {
                            id: svet
                                    z: -3
                                    y: list.currentItem.y;
                                    Behavior on y { SpringAnimation { spring: 2; damping: 0.1 } }
                                    color: "#1E90FF"
                        }
                                highlightFollowsCurrentItem: true
                                highlightMoveDuration : 100
            }
                    Component {
                        id: numberDelegate
                        RowLayout {
                            id: wrapper
                            property int number: index
                            width: ListView.view.width
                            height: 40
                            //anchors.topMargin: 300
                            z: -1
                            property var view: ListView.view
                            property var isCurrent: ListView.isCurrentItem
                            Rectangle {
                                id: rec3
                                MouseArea {
                                    id: mouse
                                    anchors.fill: parent
                                    onClicked: view.currentIndex = model.index                                                }
                                z: -4
                                width: parent.width
                                height: 40
                                color: "transparent"
                                border.color: "#353637"
                                Text {
                                    anchors.centerIn: parent
                                    font.pixelSize: 20
                                    text: Identifikator
                                }
                                Text {
                                    id: text1
                                    font.pixelSize: 10
                                    text: view.currentIndex
                                }
                            }
                        }
                    }
                transitions: Transition {
                    NumberAnimation { properties: "opacity"; duration: 400 }
                }
            }
            }
            Row {
                id: row2
                anchors.left: rec1.left
                anchors.leftMargin: 5
                anchors.right: rec1.right
                anchors.rightMargin: 5
                anchors.bottom: rec1.bottom
                anchors.bottomMargin: 5
                height: 40
                spacing: 5
                Button {                    
                    highlighted: true
                    width: row2.width / 3 - 10 / 3
                    Text {
                        id: name2
                        text: qsTr("Создать")
                        font.family: "Arial"
                        font.bold: true
                        color: "white"
                        font.pixelSize: 12
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    onClicked: {
                        var component = Qt.createComponent("BazaOborudovaniaCreat.qml")
                        var window    = component.createObject(rec0)
                        window.show()
                    }
                }
                Button {                    
                    highlighted: true
                    width: row2.width / 3 - 10 / 3
                    Text {
                        id: name3
                        text: qsTr("Редактировать")
                        font.family: "Arial"
                        font.bold: true
                        color: "white"
                        font.pixelSize: 12
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
                Button {                    
                    highlighted: true
                    width: row2.width / 3 - 10 / 3
                    Text {
                        id: name4
                        text: qsTr("Удалить")
                        font.family: "Arial"
                        font.bold: true
                        color: "white"
                        font.pixelSize: 12
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                    }                    
                    onClicked: {
                        database.removeRecord(QueryModel1.getId(view.currentIndex)) // Почему-то удаляется первый элемент списка
                        QueryModel1.updateModel();
                    }
                }
            }
        }
Rectangle {
    id: rec0
    anchors.left: rec1.right
    anchors.top: parent.top
    anchors.right: parent.right
    height: item1.height
    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: tabBar.currentIndex
        BazaOborudovania1 {
        }
        BazaOborudovania2 {
        }
        BazaOborudovania3 {
        }
        BazaOborudovania4 {
        }
    }
        TabBar {
        id: tabBar
        height: 40
        anchors.bottom: parent.bottom
        anchors.right: parent.right
        anchors.rightMargin: 0
        anchors.left: parent.left
        anchors.leftMargin: 0
        currentIndex: swipeView.currentIndex
        TabButton {
            text: qsTr("Общие данные")
            font.pixelSize: 15
            font.family: "Arial"
            font.bold: true
        }
        TabButton {
            text: qsTr("Критерии")
            font.pixelSize: 15
            font.family: "Arial"
            font.bold: true
        }
        TabButton {
            text: qsTr("Подшипники")
            font.pixelSize: 15
            font.family: "Arial"
            font.bold: true
        }
        TabButton {
            text: qsTr("История измерений")
            font.pixelSize: 15
            font.family: "Arial"
            font.bold: true
        }
    }
    }
    }
}

 

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
  • Dec. 21, 2016, 9:50 a.m.
  • The answer was marked as a solution.

Добрый день.
Что-то Вы, по-моему, перемудрили с делегатами и этим самым view.currentIndex…

Попробуйте вместо view.currentIdex использовать list.currentIndex

onClicked: {
    database.removeRecord(QueryModel1.getId(list.currentIndex)) 
    QueryModel1.updateModel();
}

 

    Евгений, спасибо! Работает. Хотя я точно помню что c list.currentIndex тоже пробовал и удаляло только первый элемент. А сейчас работает. Наверное надо почаще чистить проект.
      С QML вообще желательно почаще делать clean Project, а иногда и полностью удалять build.
      А то как попало себя ведёт.

        Comments

        Only authorized users can post comments.
        Please, Log in or Sign up
        l
        • laei
        • April 23, 2024, 9:19 a.m.

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

        • Result:10points,
        • Rating points-10
        l
        • laei
        • April 23, 2024, 9:17 a.m.

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

        • Result:50points,
        • Rating points-4
        e
        • ehot
        • March 31, 2024, 2:29 p.m.

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

        • Result:78points,
        • Rating points2
        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