
Виталий АнтиповDec. 21, 2016, 6:21 p.m.
Удаление записи из БД (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 } } } } }

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!
Ua
- Unknown akadamn
- Jan. 24, 2025, 5:14 p.m.
Qt - Test 001. Signals and slots
- Result:84points,
- Rating points4
Ua
- Unknown akadamn
- Jan. 24, 2025, 4:22 p.m.
Qt - Test 001. Signals and slots
- Result:42points,
- Rating points-8
Last comments
ИМ
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Игорь МаксимовNov. 22, 2024, 9:51 p.m.

Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
Игорь МаксимовOct. 5, 2024, 4:51 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
f
Рисование на QGraphicsScene при зажатой кнопке мыши Подскажите, пожалуйста! Как данный класс можно дополнить, чтобы созданные объекты можно было перемещать мышкой по сцене?
firstlunoxodFeb. 15, 2025, 1:46 p.m.

ДмитрийFeb. 3, 2025, 4:24 p.m.
не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.
Добрый день.
Что-то Вы, по-моему, перемудрили с делегатами и этим самым view.currentIndex…
Попробуйте вместо view.currentIdex использовать list.currentIndex
А то как попало себя ведёт.