Виталий Антипов21 декабря 2016 г. 18:21
Удаление записи из БД (Qml ListView)
На основе урока “База данных 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 } } } } }
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.Вам это нравится? Поделитесь в социальных сетях!
Комментарии
Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь
Пожалуйста, авторизуйтесь или зарегистрируйтесь
B
- Bogdannn
- 27 марта 2024 г. 19:15
C++ - Тест 001. Первая программа и типы данных
- Результат:46баллов,
- Очки рейтинга-6
Последние комментарии
Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5 февраля 2024 г. 1:50
EVA25 декабря 2023 г. 10:30
Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Сейчас обсуждают на форуме
Как получить в массив значения из связанной модели? Спасибо, разобрался:))
AC
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
Alexandru Codreanu19 января 2024 г. 11:57
BlinCT27 декабря 2023 г. 8:57
Дмитрий10 января 2024 г. 4:18
Evgenii Legotckoi12 декабря 2023 г. 6:48
Добрый день.
Что-то Вы, по-моему, перемудрили с делегатами и этим самым view.currentIndex…
Попробуйте вместо view.currentIdex использовать list.currentIndex
А то как попало себя ведёт.