QML/Python 组合框打印选中项问题

QML/Python Combobox print selected item issue

我正在使用 PySide2 并创建一个组合框,我试图在按下提交按钮时发送选定的值,视觉示例:

当按下提交时 test1 应该打印在终端上,我尝试使用插槽但是当按下提交按钮时没有任何反应。

我的代码: 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('test')
        print(text_val, self.model.text)



if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    comobo_box = Combo()

    context = engine.rootContext()
    context.setContextProperty("comobo_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_()

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

            }

        }

    }
}

问题是没有模型对象,同样假设您引用的是 ComboBox 模型,它也没有文本属性,并且在日志中指出了这一点。

file:///home/qt/main.qml:35: ReferenceError: model is not defined

在本例中,它传递的是当前文本:

comobo_box.submit(cBox.currentText)

在python这边也有类似的问题所以你必须删除self.model.text:

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