АЧ
Алексей ЧепрасовJune 27, 2016, 12:58 p.m.

Передача данных из комбобокса в строку ввода в QML

TextField, qml, ComboBox

Всем привет. Нужно передать выбранный элемент комбобокса в строку ввода текста, к примеру в “наименование товара”
Код файла с таблицей

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
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 27, 2016, 1:30 p.m.

Добрый день.
Можно реализовать это через обработчик сигнала комбобокса onCurrentTextChanged, то есть

ComboBox {
    onCurrentTextChanged: {
        fnameField.text = currentText; // Это будет как раз текущий текст в комбобоксе         
    }
}

Но учитывая, что каждый элемент модели состоит из двух полей, то правильнее будет сделать следующим образом.

import QtQuick 2.6
import QtQuick.Controls 1.5
 
ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
 
    ComboBox {
        x:50
        y:50
        editable: true
 
        model: ListModel {
            id: model
            ListElement { text: "Banana"; color: "Yellow" }
            ListElement { text: "Apple"; color: "Green" }
            ListElement { text: "Coconut"; color: "Brown" }
        }
 
        onCurrentIndexChanged: {
            fnameField.text = model.get(currentIndex).text
        }
    }
 
    TextField {
        id: fnameField
        x: 50
        y: 80
   }
}

 

    для улучшения внешнего вида у TextField добавляем параметр visible: false

    TextField {
               visible: false
            id: fnameField
            x: 50
            y: 80
       }

     

      Evgenii Legotckoi
      • June 27, 2016, 1:46 p.m.
      • The answer was marked as a solution.

      для улучшения внешнего вида у TextField добавляем параметр visible: false

      Тогда уж лучше вообще избавиться от этого лишнего элемента.
      Ведь можно же забирать данные из комбобокса и передавать их куда следует.

      import QtQuick 2.6
      import QtQuick.Controls 1.5
       
      ApplicationWindow {
          visible: true
          width: 640
          height: 480
          title: qsTr("Hello World")
       
          ComboBox {
              id: comboBox
              x:50
              y:50
              editable: true
       
              model: ListModel {
                  id: model
                  ListElement { text: "Banana"; color: "Yellow" }
                  ListElement { text: "Apple"; color: "Green" }
                  ListElement { text: "Coconut"; color: "Brown" }
              }
       
              onCurrentIndexChanged: {
                  fnameField.text = model.get(currentIndex).text
              }
          }
       
          TextField {
              id: fnameField
              x: 50
              y: 80
         }
       
          Button {
              x: 50
              y: 110
              text: "Кнопка"
              onClicked: {
                  console.log(comboBox.model.get(comboBox.currentIndex).text)
              }
          }
      }

       

        Comments

        Only authorized users can post comments.
        Please, Log in or Sign up
        d
        • dsfs
        • April 26, 2024, 4:56 a.m.

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

        • Result:80points,
        • Rating points4
        d
        • dsfs
        • April 26, 2024, 4:45 a.m.

        C++ - Test 002. Constants

        • Result:50points,
        • Rating points-4
        d
        • dsfs
        • April 26, 2024, 4:35 a.m.

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

        • Result:73points,
        • Rating points1
        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