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

How to fetch database row and display in Qlabels with QcomboBox selected value in PyQt5



  • I want to fetch database row values and display it in some labels based upon the selected value of combo box.

    The combo box successfully display 'item_name' from table_1 in the combo box. Now, I want to display 'item_name' relevant row values (like item_price, item_code, item_qty etc) in label_1, label_2, label_3 etc., whenever the combo box value changes.

    I fetch database and display in the combo box with the following code:

        ```
    

    def populate_combobox(self):
    conn = sqlite3.connect('DB.db')
    c = conn.cursor()

        c.execute("SELECT item_name FROM table_1")
    
        data = c.fetchall()
    
        self.comboBox_3.clear()
        for item_name in data:
            self.comboBox_3.addItem(item_name[0])
    
    
    
    Examples: table_1
    | id | item_name|item_code|item_qty |item_price|
    | -- |----------|---------|---------|----------|
    | 1  | mango    |MGO      | 20      | 150      | 
    | 2  | banana   |BNNA     | 5       | 120      |
    | 3  | apple    |APPL     | 15      | 180      |
    | 4  | grape    |GRPE     | 55      | 750      |
    | 5  | coconut  |CCN      | 75      | 820      |
    | 6  | pumpkin  |PPK      | 100     | 980      |
    
    My expectation:
    If combobox value 'mango' is selected:
    label_1 = MGO
    label_2 = 20
    label_3 = 150
    
    and if combobox value 'apple' is selected:
    label_1 = APPL
    label_2 = 15
    label_3 =180
    
    Thanks in advance.

  • Lifetime Qt Champion

    Hi,

    The way you do it will require you do make calls to the database every time you change the combo box selected item.

    Did you consider taking advantage of the Qt SQL module ?

    QDataWidgetMapper will also be of interest for what you want to do.



  • @SGaist Thanks for your reply. Yes, QDataWidgetMapper and or Query Model seems to be what I need. Can you please suggest where I could learn it (tutorial pages) or is there a free code sample where I could learn? (I am using PyCharm and QT Designer for UI. I am new in python and a self learner too. I don't understand C++).


  • Lifetime Qt Champion


Log in to reply