2013-02-16 3 views
1

Qsqlquer 모델에 확인란 열을 추가하고 싶습니다. 체크 박스는 데이터베이스에 연결되어 있지 않습니다. 델리게이트를 사용하는 것은 내가하려는 일에 대해 낮은 수준으로 보인다.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

다음은 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