АЧ
Алексей ЧепрасовJune 27, 2016, 12:58 p.m.
Передача данных из комбобокса в строку ввода в 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 ApplicationWindow { id:table1 visible: false width: 1700 height: 700 title: qsTr("Панель администратора") Text{ x:300 text: "" } Button { id: button text: qsTr("Выход") anchors.top: parent.top anchors.topMargin: 5 anchors.left: parent.left anchors.leftMargin: 5 onClicked: {table1.visible=false } } /* TabView, в первой вкладке которого находится кнопка, * по нажатию кнопки которой из изменится текст в первой кнопке */ TabView { id: tabView anchors.top: button.bottom anchors.topMargin: 5 anchors.left: parent.left anchors.right: parent.right anchors.bottom: parent.bottom Tab { id: tab1 title: qsTr("Товары") component: Item { id: rect1 } Rectangle{visible: true width: 1600 height: 480 // Слой с TaxtField`ами и Button для занесения записей в базу данных RowLayout { id: rowLayout anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right anchors.margins: 5 spacing: 10 Text {text: qsTr("Наименование товара")} TextField {id: fnameField } Text {text: qsTr("Категория")} TextField {id: kategoryField} Text {text: qsTr("Прибыло")} TextField { id: snameField} Text {text: qsTr("Убыло")} TextField { id: ubylField} Text {text: qsTr("Номер стеллажа")} TextField {id: nikField} Text {text: qsTr("Номер полки")} TextField {id: numberpolkField} Button { id: pusto text: qsTr("Добавить") // Вносим новую запись в базу данных MouseArea{ anchors.fill: parent onClicked: { if (fnameField.text=="" || snameField.text=="" || ubylField.text=="" || nikField.text=="" || numberpolkField.text=="" || kategoryField.text=="") { contextMenu2.popup() } if(kategoryField.text=="Овощи" ||kategoryField.text=="овощи"||kategoryField.text=="Фрукты"||kategoryField.text=="фрукты") { database.inserIntoTable( fnameField.text , kategoryField.text, snameField.text, ubylField.text, nikField.text, numberpolkField.text) myModel.updateModel() // И обновляем модель данных с новой записью } else contextMenu3.popup() } } } Button { text: qsTr("Экспорт в Excel") // Запускаем экспорт onClicked: { myModel.exportCSV() } } } TableView { id: tableView anchors.top: rowLayout.bottom anchors.left: parent.left anchors.right: parent.right anchors.bottom: parent.bottom anchors.margins: 5 TableViewColumn { role: "date" title: "Дата" } TableViewColumn { role: "time" title: "Время" } TableViewColumn { role: "fname" title: "Наименование товара" } TableViewColumn { role: "kategory" title: "Категория" } TableViewColumn { role: "sname" title: "Прибыло" } TableViewColumn { role: "ubyl" title: "Убыло" } TableViewColumn { role: "nik" title: "Номер стеллажа" } TableViewColumn { role: "numberpolk" title: "Номер полки" } model: myModel // Настройка строки в TableView для перехавата левого клика мыши 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 } } } } } // Контекстно меню предлагает удаление строки из базы данных Menu { id: contextMenu MenuItem { text: qsTr("Удалить") onTriggered: { /* Вызываем диалоговое окно, * которое уточнит намерение удалить строку из базы данных * */ dialogDelete.open() } } } // Диалог подтверждения удаления строки из базы данных MessageDialog { id: dialogDelete title: qsTr("Удаление записи") text: qsTr("Подтвердите удаление записи со склада") icon: StandardIcon.Warning standardButtons: StandardButton.Ok | StandardButton.Cancel // При положительном ответе ... onAccepted: { /* ... удаляем строку по id, * который забираем из модели данных * по номеру строки в представлении * */ database.removeRecord(myModel.getId(tableView.currentRow)) myModel.updateModel(); // Обновляем модель данных } } //Всплывающее окно если строка ввода текста пустая Menu { id: contextMenu2 MenuItem { text: qsTr("Что - то пошло не так :С") onTriggered: { dialogNULL.open() } } } // Диалог подтверждения удаления строки из базы данных MessageDialog { id: dialogNULL title: qsTr("Одна или несколько строк не заполнены") text: qsTr("Проверьте, все ли строки заполнены и добавте запись в таблицу") icon: StandardIcon.Warning standardButtons: StandardButton.Ok | StandardButton.Cancel // При положительном ответе ... onAccepted: { dialogNULL.visible=false } } Menu { id: contextMenu3 MenuItem { text: qsTr("Аяяй :С") onTriggered: { dialogOvosh.open() } } } MessageDialog { id: dialogOvosh title: qsTr("Склад овощей!!!") text: qsTr("На складе нельзя хранить что - то, кроме овощей и фруктов") icon: StandardIcon.Warning standardButtons: StandardButton.Ok | StandardButton.Cancel // При положительном ответе ... onAccepted: { dialogOvosh.visible=false } } ComboBox { x:100 y:300 editable: true model: ListModel { id: model ListElement { text: "Banana"; color: "Yellow" } ListElement { text: "Apple"; color: "Green" } ListElement { text: "Coconut"; color: "Brown" } } onAccepted: { if (find(currentText) === -1) { model.append({text: editText}) currentIndex = find(editText) fnameField.insert(currentIndex) } } } } } } }
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!
- Дмитрий
- May 7, 2024, 9:40 p.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:60points,
- Rating points-1
d
- dsfs
- April 26, 2024, 4:56 p.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:80points,
- Rating points4
Last comments
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий КононенкоFeb. 5, 2024, 2:50 p.m.
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCTMay 5, 2024, 5:46 p.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii LegotckoiMay 3, 2024, 2:07 a.m.
IscanderCheApril 30, 2024, 4:22 p.m.
Добрый день.
Можно реализовать это через обработчик сигнала комбобокса onCurrentTextChanged, то есть
Но учитывая, что каждый элемент модели состоит из двух полей, то правильнее будет сделать следующим образом.
для улучшения внешнего вида у TextField добавляем параметр visible: false
Тогда уж лучше вообще избавиться от этого лишнего элемента.
Ведь можно же забирать данные из комбобокса и передавать их куда следует.