Skip to content

Instantly share code, notes, and snippets.

@nicelifeBS
Created September 5, 2016 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicelifeBS/8e96a149d6876861f0e4c91d3be8efe3 to your computer and use it in GitHub Desktop.
Save nicelifeBS/8e96a149d6876861f0e4c91d3be8efe3 to your computer and use it in GitHub Desktop.
QItemDelegate and QAbstractListModel
import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui
class SpinBoxDelegate(QtGui.QItemDelegate):
def createEditor(self, parent, option, index):
editor = QtGui.QSpinBox(parent)
editor.setMinimumHeight(100)
return editor
def paint(self, painter, option, index):
super(SpinBoxDelegate, self).paint(painter, option, index)
def sizeHint(self, option, index):
if option.state & QtGui.QStyle.State_Enabled:
editor = self.createEditor(None, option, index)
return editor.sizeHint()
else:
return index.data().sizeHint()
def setEditorData(self, spinBox, index):
value = index.model().data(index, QtCore.Qt.EditRole)
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 MyListModel(QtCore.QAbstractListModel):
def __init__(self, parent=None):
QtCore.QAbstractListModel.__init__(self, parent)
self.listdata = [1,2,3,5,8,13]
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.listdata)
def data(self, index, role):
if not index.isValid():
print "index not valid"
elif role == QtCore.Qt.DisplayRole:
return self.listdata[index.row()]
elif role == QtCore.Qt.EditRole:
return self.listdata[index.row()]
else:
return None
def setData(self, index, value, role):
if role == QtCore.Qt.EditRole:
self.listdata[index.row()] = value
def flags(self, index):
if not index.isValid():
return QtCore.Qt.NoItemFlags
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled
def addItems(self, data, position):
self.beginInsertRows(QtCore.QModelIndex(), position, position)
self.listdata.append(data)
self.endInsertRows()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
model = MyListModel()
listView = QtGui.QListView()
listView.setModel(model)
delegate = SpinBoxDelegate()
listView.setItemDelegate(delegate)
listView.setWindowTitle("Spin Box Delegate")
listView.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment