PyQt. How to insert a widget in a QTableView
Asked Answered
G

1

6

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()

Gisborne answered 6/11, 2017 at 15:7 Comment(2)
@eyllanesc It has matter? I want simply add a button in a table even if it will has no actionGisborne
@eyllanesc in general this button launch a big function, that use index of table cellGisborne
A
7

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

Arise answered 6/11, 2017 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.