我想在Qsqlquerymodel中添加一列复选框。复选框未链接到数据库。对于我想要做的事情,使用代表似乎很低级别。
我想使用的代码将基于(PyQt):
model = QtSql.QSqlQueryModel()
model.insertColumn(2) #checkbox column
checkboxes = list() #Used later to check checkboxe state
for i in range(0, model.rowCount()):
checkboxes.append((i, QtGui.QCheckBox())) #store row and checkbox in list
model.addWidget(i, 2, checkboxes[-1][1]) #addWidget in row(i), col(2) does not exist :(
答案 0 :(得分:1)
我在Sibylle Koczian工作之后通过继承QsqlQueryModel来管理。
class CheckboxSqlModel(QtSql.QSqlQueryModel):
def __init__(self, column):
super(CheckboxSqlModel, self).__init__()
self.column = column
self.checkboxes = list() #List of checkbox states
self.first = list() #Used to initialize checkboxes
#Make column editable
def flags(self, index):
flags = QtSql.QSqlQueryModel.flags(self, index)
if index.column() == self.column:
flags |= QtCore.Qt.ItemIsUserCheckable
return flags
def data(self, index, role=QtCore.Qt.DisplayRole):
row = index.row()
if index.column() == self.column and role == QtCore.Qt.CheckStateRole:
#Used to initialize
if row not in self.first :
index = self.createIndex(row, self.column)
self.first.append(row)
self.checkboxes.append(False)
return QtCore.Qt.Unchecked
#if checked
elif self.checkboxes[row]:
return QtCore.Qt.Checked
else:
return QtCore.Qt.Unchecked
else:
return QtSql.QSqlQueryModel.data(self, index, role)
def setData(self, index, value, role=QtCore.Qt.DisplayRole):
row = index.row()
if index.column() == self.column and role == QtCore.Qt.CheckStateRole:
if value.toBool():
self.checkboxes[row] = True
else:
self.checkboxes[row] = False
self.dataChanged.emit(index, index)
return True
else:
return False