Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Pyside Combobox print selected item issue



  • New to qml, but maybe someone will be able to help me out,
    I'm using PySide2 and creating a combobox, I'm trying to send the selected value when pressing the submit button, visual example:
    45b7018a-0372-4c83-ae21-68cc79b82e1e-image.png ,
    when pressing submit test1 should be print on teminal, I tried using Slots but when pressing on the submit button nothing happens.

    my code:
    main.qml:

    import QtQuick 2.15
    import QtQuick.Window 2.15
    import QtQuick.Layouts 1.15
    import QtQuick.Controls 2.15

    Window {
    id: window
    visible: true
    height: 200
    width: 400

    property string textVal: ""
    
    Rectangle {
        color: '#041645'
        id: mainArea
        anchors.fill: parent
        ColumnLayout {
            anchors.fill: parent
    
            ComboBox {
                id: cBox
                Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
                model: stringModel
                textRole: "display"
    
    
                    Button {
                    id: submit
                    x: -50
                    y: 100
                    text: qsTr("Submit")
                    onClicked: {
                        comobo_box.submit(model.text)
                       }
                }
                    Button {
                    id: cancel
                    x: 75
                    y: 100
                    text: qsTr("Cancel")
                    onClicked: {
                        window.close()
    
                                    }
                }
    
    
            }
            RowLayout{
                    Layout.alignment: Qt.AlignHCenter
    
            }
    
        }
    
    }
    

    }

    main.py:

    import sys
    import os
    from os.path import join, dirname, abspath
    from PySide2.QtCore import QStringListModel, QObject, Slot
    from PySide2.QtGui import QGuiApplication
    from PySide2.QtQml import QQmlApplicationEngine

    class Combo(QObject):
    def init(self, parent=None):
    super().init()
    self.model = QStringListModel(['test1', 'test2'])

    @Slot(str, result=None)
    def submit(self, text_val):
    
        print(text_val)
    

    if name == 'main':
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    comobo_box = Combo()
    
    context = engine.rootContext()
    context.setContextProperty("combo_box", comobo_box)
    context.setContextProperty("stringModel", comobo_box.model)
    qmlFile = join(dirname(__file__), r'main.qml')
    engine.load(abspath(qmlFile))
    
    
    if not engine.rootObjects():
        sys.exit(-1)
    
    app.exec_()

Log in to reply