照着《C++ Gui Qt 编程》里照葫芦画飘成功了,我好棒棒
添加QComBox也成功
class SpinBoxDelegate(QItemDelegate):
def __init__(self, column, parent=None):
super(SpinBoxDelegate, self).__init__(parent)
self.column = column
def paint(self, painter, option, index):
if index.column() == self.column:
value = index.model().data(index, Qt.DisplayRole)
option.displayAlignment = Qt.AlignRight | Qt.AlignVCenter
self.drawDisplay(painter, option, option.rect, str(value) if value is not None else None)
self.drawFocus(painter, option, option.rect)
else:
super(SpinBoxDelegate, self).paint(painter, option, index)
def createEditor(self, parent, option, index):
if index.column() == self.column:
spinBox = QSpinBox(parent)
spinBox.setRange(0, 2000)
spinBox.editingFinished.connect(self.commitAndCloseEditor)
return spinBox
else:
return super(SpinBoxDelegate, self).createEditor(parent, option, index)
def commitAndCloseEditor(self):
spinBox = self.sender()
self.commitData.emit(spinBox)
self.closeEditor.emit(spinBox)
def setEditorData(self, editor, index):
if index.column() == self.column:
value = index.model().data(index, Qt.DisplayRole)
editor.setValue(value if value is not None else 0)
else:
super(SpinBoxDelegate, self).setEditorData(editor, index)
使用:
class TableView(QTableView):
def __init__(self, parent=None):
super(TableView, self).__init__(parent):
self.model = QStandardItemModel(self)
self.setModel(self.model)
spinBoxDelegate = SpinBoxDelegate(1) # 对第2列有效
self.setItemDelegate(spinBoxDelegate)