Generally they way you would use model/view architecture is the model stores all your data and the view would actually display that data. You would not store a widget in the model, you would store your data for that cell in the model, but how that data shows up is up to the view. Reading the help file
The items shown in a table view, like those in the other item views, are rendered and edited using standard delegates. However, for some tasks it is sometimes useful to be able to insert widgets in a table instead. Widgets are set for particular indexes with the setIndexWidget() function, and later retrieved with indexWidget().
So if need a particular widget to show up in a specific cell I would look at the TableView class instead. If you just want to be able to edit the info in the cell have a look at this example
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index, role):
if role == Qt.DisplayRole or role == Qt.EditRole:
# See below for the nested-list data structure.
# .row() indexes into the outer list,
# .column() indexes into the sub-list
return self._data[index.row()][index.column()]
def setData(self, index, value, role):
self._data[index.row()][index.column()] = value
return super(TableModel, self).setData(index, value, role)
def rowCount(self, index):
# The length of the outer list.
return len(self._data)
def columnCount(self, index):
# The following takes the first sub-list, and returns
# the length (only works if all rows are an equal length)
return len(self._data[0])
def flags(self, index): # Qt was imported from PyQt4.QtCore
if index.column() < 2:
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
else:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
class MyDelegate(QtWidgets.QItemDelegate):
def __init__(self):
super().__init__()
def createEditor(self, parent, option, index):
if index.column() < 2:
return super(MyDelegate, self).createEditor(parent, option, index)
else:
return None
def setEditorData(self, editor, index):
if index.column() < 2:
# Gets display text if edit data hasn't been set.
text = (index.data(Qt.EditRole) or index.data(Qt.DisplayRole))
editor.setText(text)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
data = [
["4", "9", "2"],
["4", "9", "2"],
["4", "9", "2"],
["4", "9", "2"],
["4", "9", "2"]
]
self.model = TableModel(data)
self.table.setModel(self.model)
self.delegate = MyDelegate()
self.table.setItemDelegate(self.delegate)
self.setCentralWidget(self.table)
app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()