python - 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])
解决方案
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])
推荐阅读
- html - HTML / CSS:如何设置 Div 的样式,使其与 Bootstrap 按钮的样式/行为相匹配
- python-2.7 - 如何在一行中多次创建相同但独立的字典结构?
- python - Sentry.io API 获取过滤环境标签的问题
- javascript - HTML选择下拉菜单不更改页面数据
- oauth - 带有 SPA 的 Jira Server OAuth 1.0a 身份验证
- python - Scikit fit_transform、ColumnTransformer 和 OneHotEncoder 的目的不就是对分类数据进行编码,那为什么还要用在数值上呢?
- github - 尝试使用 API 调用提交到 GitHub
- azure - 无法访问 onedrive
- nestjs - 如何从处理请求的服务中获取模块的名称?
- node.js - SQS 队列集成架构