简体   繁体   中英

Python - Add checkbox to every row in QTableWidget

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:

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)
self.ui.tableWidget.setColumnCount(4)
self.ui.tableWidget.setRowCount(4)
self.ui.tableWidget.verticalHeader().setVisible(False)
self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

alaaa = ['Source Image', 'Dimension', 'Format', "File size"]
self.ui.tableWidget.setHorizontalHeaderLabels(alaaa)

for row, string in enumerate(alaaa, 0):
    chkBoxItem = QTableWidgetItem(string)
    chkBoxItem.setText(string)
    chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
    self.ui.tableWidget.setItem(row, 0, chkBoxItem)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM