Reputation: 71
There is a table:
tab=QTableView()
sti=QStandardItemModel(parent=None)
sti.appendRow([QStandardItem(str(1)),QStandardItem(str(2)),QStandardItem(str(3)),QStandardItem(str(4))])
tab.setModel(sti)
tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
There is a button:
btn=QPushButton('Press', self)
btn.clicked.connect(self.on_clicked)
btn.resize(btn.sizeHint())
Task: How can I insert button btn in the table cell insert of QStandardItem(str(4))? There is a method .setCellWidget() of class QTableWidget for it, but I inherited from QTableView. If I'll use QTableWidget I'll can't use private method .setModel()
Upvotes: 6
Views: 9750
Reputation: 244282
To be able to insert a widget you must use the setIndexWidget()
method where the QModelIndex()
associated to the cell must be passed as the first parameter, considering that the indexes of the row and column start from 0, for the item with text equal to str(4)
its coordinate is 0, 3
:
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
app.setStyle("fusion")
tab = QTableView()
sti = QStandardItemModel()
sti.appendRow([QStandardItem(str(i)) for i in range(4)])
tab.setModel(sti)
tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
tab.setIndexWidget(sti.index(0, 3), QPushButton("button"))
tab.show()
sys.exit(app.exec_())
if you have the QStandardItem()
you can also access the QModelIndex
through the indexFromItem()
method
Upvotes: 7