将小部件添加到Qsqlquerymodel

时间:2013-02-16 15:59:11

标签: qt pyqt

我想在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 :(
  • 是否可以不使用代理,因此代码更简单?
  • 我应该使用布局而不是在模型中包含复选框吗?
  • 我错过了一个简单的解决方案吗?

1 个答案:

答案 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