为每一行 PyQt5 的特定列添加一个 QComboBox

Adding a QComboBox for specific columns for each row PyQt5

我有一个 QT Table 小部件,我从 sql 获取数据,我想在第 4、5、6 和 7 列中放置一个组合框(现在我们只做它对于第 4 列)。我做到了,但是当我执行代码时,我的 QComboBox 只显示在最后一行,这是因为我有一个 for 循环在 table 中插入行,我把 self.table.setCellWidget(row, column , combobox) 在这个循环中,所以每次执行时它都会将组合框移动到最后一行,我怎样才能为每一行设置一个组合框?这是我的代码

 def datitabella(self):    
    delegate = MyDelegate(self)
    tablerow = 0 
    conteggio = c.execute('SELECT COUNT(ID) FROM Viaggi').fetchone()[0]
    combo = QComboBox()
    for p in c.execute("SELECT Customer_code FROM Customers "):
        combo.addItem(str(p))         
    for row in c.execute("SELECT * FROM Viaggi "):
        righe = 0 
        self.tabella_registrazioni.setRowCount(conteggio)
        self.tabella_registrazioni.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(str(row[0])))
        self.tabella_registrazioni.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))
        self.tabella_registrazioni.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))
        self.tabella_registrazioni.setItem(tablerow, 3, QtWidgets.QTableWidgetItem(row[3]))
        self.tabella_registrazioni.setItem(tablerow, 4, QtWidgets.QTableWidgetItem(row[4]))
        self.tabella_registrazioni.setItem(tablerow, 5, QtWidgets.QTableWidgetItem(row[5]))
        self.tabella_registrazioni.setItem(tablerow, 6, QtWidgets.QTableWidgetItem(row[6]))
        self.tabella_registrazioni.setItem(tablerow, 7, QtWidgets.QTableWidgetItem(row[7]))
        self.tabella_registrazioni.setItem(tablerow, 19, QtWidgets.QTableWidgetItem(str(row[19])))
        self.tabella_registrazioni.setCellWidget(tablerow, 4, combo)
        tablerow+= 1           
    self.tabella_registrazioni.itemChanged.connect(self.changeIcon) 
    self.tabella_registrazioni.setItemDelegateForColumn(0, delegate)

您必须为每一行创建一个新的 QComboBox:

def datitabella(self):    
    delegate = MyDelegate(self)
    tablerow = 0
    conteggio = c.execute('SELECT COUNT(ID) FROM Viaggi').fetchone()[0]
    items = []
    for p in c.execute("SELECT Customer_code FROM Customers "):
        items.append(p[0])         
    for row in c.execute("SELECT * FROM Viaggi "):
        combo = QComboBox()
        combo.addItems(items)
        # ...
        self.tabella_registrazioni.setCellWidget(tablerow, 4, combo)