PyQt4 and QTableView with spinbox and checkbox

Posted by ekapek on Stack Overflow See other posts from Stack Overflow or by ekapek
Published on 2010-06-02T20:46:05Z Indexed on 2010/06/02 21:04 UTC
Read the original article Hit count: 1104

Filed under:
|
|

Hi,

I have a QTableView with QSqlTableModel and with 3 columns, now I need to have:
- second column: spinbox after clicked to edit
- third column: checkbox (displayed center)

My code:

class SpinBoxDelegate(QtGui.QItemDelegate):
def createEditor(self, parent, option, index):
    editor = QtGui.QSpinBox(parent)
    editor.setMinimum(0)
    editor.setMaximum(100)
    print 'spinbox'
    return editor

def setEditorData(self, spinBox, index):
    value = index.model().data(index, QtCore.Qt.EditRole).toInt()[0]

    spinBox.setValue(value)

def setModelData(self, spinBox, model, index):
    spinBox.interpretText()
    value = spinBox.value()

    model.setData(index, value, QtCore.Qt.EditRole)

def updateEditorGeometry(self, editor, option, index):
    editor.setGeometry(option.rect)

class myQSqlTableModel(QtSql.QSqlTableModel):
def flags(self,index):
    result = QtSql.QSqlTableModel.flags(self,index);
    if index.column() == 2:
        result |= QtCore.Qt.ItemIsUserCheckable
    return result
def data(self,index,role):
    if not index.isValid: return QtCore.QVariant()

    value = QtSql.QSqlTableModel.data(self, index, role)
    if index.column() == 2:
        if role == QtCore.Qt.CheckStateRole:
            return QtCore.Qt.Unchecked if QtSql.QSqlTableModel.data(self, index).toInt()[0] else QtCore.Qt.Checked 
        elif role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
    return value

and

    self.model = myQSqlTableModel(self)
    self.model.setTable("person")
    self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
    self.model.select():


    self.model.setHeaderData(0, QtCore.Qt.Horizontal,
                             self.tr("ID"))
    self.model.setHeaderData(1, QtCore.Qt.Horizontal,
                             self.tr("A"))
    self.model.setHeaderData(2, QtCore.Qt.Horizontal,
                             self.tr("B"))

    self.view = QtGui.QTableView()
    self.view.setModel(self.model)
    self.view.setSortingEnabled(True)

    spinDelegate = SpinBoxDelegate()
    self.view.setItemDelegateForColumn(1,spinDelegate)

but it does't work: spinbox don't show after click and checkbox can't be clicked and is aligned to left

Any help?

© Stack Overflow or respective owner

Related posts about pyqt

Related posts about tableview