如何在 QTableWidget 中将布尔项显示为复选框?

How can I display boolean item as checkbox in QTableWidget?

我是 Pyside 的新手,我想在 tablewidget

中显示一个布尔数据类型作为复选框

我曾尝试使用 QTableWidgetItem 重建数据,但没有成功(请参阅注释部分)

rows = [('Test1123456789', False), ('Test2123456789', False), ('Test3123456789', True), ('Test4123456789', True)]

    #rows2 = []

    # self.checkbox2 = QtWidgets.QTableWidgetItem()
    # self.checkbox2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)

    # #for i in rows:
    #   #print(i)
    #   #if i[1] == False:
    #       #self.newi = self.checkbox2
    #       self.newi = self.newi.setCheckState(QtCore.Qt.Unchecked)
    #       rows2.append((i[0],self.newi))
    #   else:
    #       self.newi = self.checkbox2
    #       self.newi = self.newi.setCheckState(QtCore.Qt.Checked)
    #       rows2.append((i[0],self.newi))

    for row_number, row_data in enumerate(rows):
        self.classestable.insertRow(row_number)
        for colum_number, data in enumerate(row_data):
            colum_number = colum_number +1
            self.checkbox = QtWidgets.QTableWidgetItem()
            self.checkbox.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            self.checkbox.setCheckState(QtCore.Qt.Unchecked)
            self.classestable.setItem(row_number,0,self.checkbox)
            self.classestable.setItem(row_number,colum_number,QtWidgets.QTableWidgetItem(str(data)))
    self.classestable.resizeColumnsToContents()

我想 return 在 table

CheckBox(Unchecked), Test1123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test2123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test3123456789, CheckBox(Checked)
CheckBox(Unchecked), Test4123456789, CheckBox(Checked)

与第1列的情况类似,但您必须根据情况使用Qt::CheckedQt::UnChecked

from PySide2 import QtCore, QtGui, QtWidgets

rows = [('Test1123456789', False), ('Test2123456789', False), ('Test3123456789', True), ('Test4123456789', True)]

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.classestable = QtWidgets.QTableWidget(0, 3)
        self.setCentralWidget(self.classestable)

        for r, (text, state) in enumerate(rows):
            it_1 = QtWidgets.QTableWidgetItem()
            it_1.setFlags(it_1.flags() | QtCore.Qt.ItemIsUserCheckable)
            it_1.setCheckState(QtCore.Qt.Unchecked)
            it_2 = QtWidgets.QTableWidgetItem(text)
            it_3 = QtWidgets.QTableWidgetItem()
            it_3.setFlags(it_3.flags() | QtCore.Qt.ItemIsUserCheckable)
            it_3.setCheckState(QtCore.Qt.Checked if state else QtCore.Qt.Unchecked)
            self.classestable.insertRow(self.classestable.rowCount())
            for c, item in enumerate([it_1, it_2, it_3]):
                self.classestable.setItem(r, c, item)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())