I am trying to add item in a QComboBox in PyQt5 using Python. I am having problems in adding data from the SQL Query per row.
cursor = cnx.cursor() query = "SELECT buyerID, lastName, firstName, middleName FROM buyer ORDER BY id DESC LIMIT 5" cursor.execute(query) data = cursor.fetchall() item = list() for a, b, c, d in data: row = "{} | {}, {} {}".format(a, b, c, d) item.append(row) self.customerID.addItem(str(item))
This results to only a single item added into the Combo Box:
100000 | lastName, firstName middleName, 100000 | lastName, firstName middleName, 100000 | lastName, firstName middleName...etc.
What I want to happen in the ComboBox is like this (Add a total of 5 items in the Combo Box)
100001 | lastName, firstName middleName 100002 | lastName, firstName middleName 100003 | lastName, firstName middleName 100004 | lastName, firstName middleName 100005 | lastName, firstName middleName
Edit:
cursor = cnx.cursor() query = "SELECT buyerID, lastName, firstName, middleName FROM buyer ORDER BY id DESC LIMIT 5" cursor.execute(query) data = cursor.fetchall() item = list() for a, b, c, d in data: row = "{} | {}, {} {}".format(a, b, c, d) item.append(row) self.customerID.addItem(str(item)) <------- I just moved this line of code into the FOR loop statement to add the item per loop.
Same Problem:
The appended Item added is still all the rows of data grouped into one.
Advertisement
Answer
After posting my question and tinkering on myself, I stumbled upon the answer to my question as I realized that I had to change the FOR LOOP statement to enumerate over the length of the data from MySQL Query Result and .addItem to the ComboBox before it goes on to the next tuple from the results from data (SQL Query Result).
for a in enumerate(data): <--- changed the for loop statement to "enumerate" how many data inside the MySQL Query Result j, k = a <--- split (index, tuple) in a l, m, n, o = k <--- separate tuple into strings string = "{} | {}, {} {}".format(l, m, n, o) self.customerID.addItem(str(string)) <------- I just moved this line of code into the FOR loop statement to add the item before moving on to the next row in SQL results.