首页 > 解决方案 > Adding items to a QComboBox adds blank items

问题描述

I am adding items to a QComboBox through a for cycle which is within a function that is called by pressing a button. As you can see in the code below I am calling data from a database, specifically from SQLite, which is filtered through a variable, this is: depid. The function performs well when called and fills in the respective QComboBox, but when called again, although it still keeps the respective elements, it adds a blank item, when I press the button again, the QComboBox keeps the elements, keeps the previous blank item and adds another, that is, each time I call the function adds a blank item.

Cur.execute("SELECT * FROM workers WHERE departament = "+str(depid))
workfilter = Cur.fetchall()

for n,data in enumerate(workfilter):
    self.BoxFilteredWorer.addItem("")
    self.BoxFilteredWorer.setItemText(n, data[1])

标签: pythonpython-3.xpyqtpyqt5qcombobox

解决方案


Explanation:

The addItem(s) method add new item with text "s" in the final position and setItemText(i, s) replaces the text of the ith item with "s".

To understand the error I will use the following example: let's say that on the first click 3 items with empty text are added and they are set as text "a", "b" and "c" of the 1st, 2nd and 3rd item, respectively, in the second click 3 new items with empty text will be added so there will be 6 items: "a", "b", "c", "", "" and "" but you replace the 1st, 2nd and 3rd with 3 texts "x", "y" and "z" so in the end there would be the 6 items: "x", "y", "z", "", "" y "".

Solution:

It is not necessary to use addItem() with setItemText(), just clean the QComboBox before the loop and add new items, in addition the enumerate is not necessary.

On the other hand do not use concatenation to create an SQL query since it makes your code susceptible to SQL Injection, instead use placeholders.

Cur.execute("SELECT * FROM workers WHERE departament = ?", (depid,))
workfilter = Cur.fetchall()

self.BoxFilteredWorer.clear()
for data in workfilter:
    self.BoxFilteredWorer.addItem(data[1])

推荐阅读