我正在嘗試使用 Python 在 PyQt5 的 QComboBox 中添加項目。我在從每行 SQL 查詢添加數據時遇到問題。
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))
這導致只有一個項目添加到組合框中:
100000 | lastName, firstName middleName, 100000 | lastName, firstName middleName, 100000 | lastName, firstName middleName...etc.
我想在ComboBox中發生的事情是這樣的(在Combo Box中總共添加5個項目)
100001 | lastName, firstName middleName
100002 | lastName, firstName middleName
100003 | lastName, firstName middleName
100004 | lastName, firstName middleName
100005 | lastName, firstName middleName
編輯:
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.
同樣的問題:
添加的appended Item仍然是將所有數據行歸為一個。
在發布我的問題並對自己進行修補後,我偶然發現了我的問題的答案,因為我意識到我必須更改 FOR LOOP 語句以在數據長度從 MySQL Query Result 和.addItem枚舉到 ComboBox 之前從數據結果(SQL 查詢結果)轉到下一個元組。
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句