Search code examples
qmlpyside2

Send string signal from combobox in qml


I'm trying to send a string from combobox to an api. Unfortunately nothing is being sent.

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
    id: mainWindow
    width: 1120
    height: 680
    visible: true

    Rectangle {
        id: mainBody
        color: "#F4F4F5"
        anchors.fill: parent

        ComboBox {
            id: comboBox
                x: 219
                y: -9
                width: 504
                height: 40
                model: [ "hp", "lenovo", "acer"]
        }
        Button {
            id: bt
            width: 24
            height: 24
            onClicked: backend.add(comboBox.text)
        }
    }
    Connections {
        target: backend
    }
}

main.py

# This Python file uses the following encoding: utf-8
import os
# from pathlib import Path
import sys
import json
import requests
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import Slot, Signal, QObject

class MainWindow(QObject):
    def __init__(self):
        QObject.__init__(self)

    signalcombo = Signal(str)
    @Slot(str, str, str)

    def add(self, getCombo):
        putdata1 = {"category_name": getCombo}
        data1 = 
        requests.post("random api", json=putdata1)
        print(data1.text)
if __name__ == "__main__":
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    # engine.load(os.fspath(Path(__file__).resolve().parent / "qml/main.qml"))
    engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))

    # Get Context
    main = MainWindow()
    engine.rootContext().setContextProperty("backend", main)
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

Now the problem is that when data1.text is printed it says "Inserted Successfully", but there is nothing in the database not even blank space. No data is being sent. Can anyone help me. This approach is working for textField but not for combobox.


Solution

  • There are various problems with your code.

    First of all, the slot decorator for add has the wrong number of arguments. In the QML you're calling it with only one argument, but the slot has three. Change it to:

        @Slot(str)
        def add(self, getCombo):
            # ...
    

    Then, ComboBox has no property named text, but currentText (or any other valid property available for it, like displayText).

            Button {
                id: bt
                width: 24
                height: 24
                onClicked: backend.add(comboBox.currentText)
            }
    

    Finally, while not critical, you should first set the context, and then load the QML:

        main = MainWindow()
        engine.rootContext().setContextProperty("backend", main)
        engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))