Python - Add checkbox to every row in QTableWidget

Joseph picture Joseph · Sep 15, 2016 · Viewed 7.4k times · Source

I am trying to add a checkbow to every row in a QTableWidget, unfortunately it only seems to appear in the first row. Here is my code:

data = ['first_row', 'second_row', 'third_row']
nb_row = len(data)
nb_col = 2

qTable = self.dockwidget.tableWidget
qTable.setRowCount(nb_row)
qTable.setColumnCount(nb_col)
chkBoxItem = QTableWidgetItem()

for row in range(nb_row):
    for col in [0]:
        item = QTableWidgetItem(str(data[row]))
        qTable.setItem(row,col,item)
    for col in [1]:
        chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
        chkBoxItem.setCheckState(QtCore.Qt.Unchecked)       
        qTable.setItem(row,col,chkBoxItem)

Am I missing something obvious?

I checked the following posts also:

Answer

Joseph picture Joseph · Sep 15, 2016

Ok, I just had to put chkBoxItem = QTableWidgetItem() inside the last loop (I guess it has to create a new QTableWidgetItem() item for each row...):

for col in [1]:
    chkBoxItem = QTableWidgetItem()
    chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    chkBoxItem.setCheckState(QtCore.Qt.Unchecked)       
    qTable.setItem(row,col,chkBoxItem)