1

我正在尝试为 QTableWidget 中的每一行添加一个复选框,不幸的是它似乎只出现在第一行。这是我的代码:

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)

我错过了一些明显的东西吗?

我还检查了以下帖子:

4

2 回答 2

6

好的,我只需要放入chkBoxItem = QTableWidgetItem()最后一个循环(我想它必须QTableWidgetItem()为每一行创建一个新项目......):

for col in [1]:
    chkBoxItem = QTableWidgetItem()
    chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    chkBoxItem.setCheckState(QtCore.Qt.Unchecked)       
    qTable.setItem(row,col,chkBoxItem)
于 2016-09-15T12:48:59.683 回答
2
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)

在此处输入图像描述

于 2021-05-21T13:43:29.117 回答