PyQT5 - Button to add row to a QTableView
-
Hello, for some reason this doesn't work for me in my app:
# within the app's class def __init__(self): super(myApp, self).init() self.ui = Ui_MainWindow() # loaded with uic self.ui.setupUi(self) self.model = QStandardItemModel() self.table = QTableView() self.table.setModel(self.model) self.ui.pageLayout.addWidget(self.table) self.addRowBtn = QtWidget.QPushButton() self.addRowBtn.clicked.connect(self.addRowBtn_clicked) self.ui.pageLayout.addWidget(self.addRowBtn) def addRow(self, table, model): indices = table.selectionModel().selectedRows() # in case none selected or no table to select if len(indices) == 0 : model.insertRow(0) else: for index in sorted(indices): model.insertRow(index) @QtCore.pyqtSlot() def addRowBtn_clicked(self): self.addRow(self.table,self.model)
I made a button for the addRow function and connected it through a pyqtslot but nothing happens when I click it. No errors either. When the program starts the table is completely blank, how do I add the first blank cell to the tableview then keep adding? I have a near identical function for adding columns, too. Very simple!
Thank you.
-
Hi,
Can you show how you setup your signals and slots ?
-
@mootytootyfrooty said in PyQT5 - Button to add row to a QTableView:
insertRow
Hi
What model do you use for the view ? -
Hi
Maybe its due to python syntax but i dont see you set the items text anywhere ?
bool QStandardItemModel::insertRow(int row, const QModelIndex & parent = QModelIndex())
only inserts an empty row (of items)
The other insertRow takes a list, likeQStandardItemModel m(3,3); QList<QStandardItem*> newRow; for (int i=0;i<model.colCount();i++) { QStandardItem* itm = new QStandardItem(QString("data for col %1").arg(i)); newRow.append(itm); } model.append(newRow);
Where you new the items yourself and hence can give them text.
When you use
bool insertRow ( int row, const QModelIndex & parent = QModelIndex() )
you need to acces the items and set the text after.