如何在 QTableWidget 中将布尔项显示为复选框?
Posted
技术标签:
【中文标题】如何在 QTableWidget 中将布尔项显示为复选框?【英文标题】:How can I display boolean item as checkbox in QTableWidget? 【发布时间】:2019-01-22 18:56:02 【问题描述】:我是 Pyside 的新手,我想在表格小部件中将布尔数据类型显示为复选框
我尝试使用 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()
我想让它返回到表格中
CheckBox(Unchecked), Test1123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test2123456789, CheckBox(Unchecked)
CheckBox(Unchecked), Test3123456789, CheckBox(Checked)
CheckBox(Unchecked), Test4123456789, CheckBox(Checked)
【问题讨论】:
【参考方案1】:与第1列的情况类似,但必须根据情况使用Qt::Checked
或Qt::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_())
【讨论】:
谢谢!刚刚捐赠。快速提问,在代码的if state else
部分,您为什么不必指定真假?,再次感谢@eyllanesc以上是关于如何在 QTableWidget 中将布尔项显示为复选框?的主要内容,如果未能解决你的问题,请参考以下文章
如何在一个QTableWidget对象中将某一列单元格设置成QComboBox