【问题标题】:Add widget to Qsqlquerymodel将小部件添加到 Qsqlquerymodel
【发布时间】:2013-03-17 01:25:02
【问题描述】:

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

【问题讨论】:

    标签: qt pyqt


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 2017-07-11
      • 2013-05-23
      • 2013-06-03
      • 1970-01-01
      • 2012-08-14
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多