We have known how to save data into a table in pyqt. Here is an example:
PyQT Add and Show a Table: A Beginner Guide
However, these data is not saved row by row. To address this issue, we will write an example to how to add data in pyqt table row by row in this tutorial.
Create a pyqt table
We first create a table without any data.
import sys from PyQt5.QtWidgets import QApplication, QWidget,QPushButton, QHBoxLayout, QVBoxLayout from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem from PyQt5 import QtCore class YuTextFrame(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('PyQT Table Add Row Data Dynamically') vbox = QVBoxLayout() # add table table = QTableWidget(self) table.setColumnCount(5) table.rowCount() #set table header table.setHorizontalHeaderLabels(['id','Name','Age','Sex','Address']) #add data row_1 = ['001', 'John', 30, 'Male', 'Street No 2'] row_2 = ['002', 'Lily', 32, 'Female', 'Street No 1'] row_3 = ['003', 'Kate', 20, 'Male', 'Street No 3'] row_4 = ['004', 'Tom', 22, 'Male', 'Street No 4'] vbox.addWidget(table) self.setLayout(vbox) self.setGeometry(300,400,500,400) self.show() if __name__ == '__main__': app = QApplication(sys.argv) frame = YuTextFrame() sys.exit(app.exec_())
In code above, we only set table column is 5 and does not set the row count. Then, we will add 4 row data into this table.
You will find this table likes:
Add data row by row
To add data row by row, we should change the row count dynamically.
row = table.rowCount() table.setRowCount(row+1)
Then we we can add a row data.
We will create a function to add data row by row.
def addTableRow(self, table, row_data): row = table.rowCount() table.setRowCount(row+1) col = 0 for item in row_data: cell = QTableWidgetItem(str(item)) table.setItem(row, col, cell) col += 1
In this code, we will add a row data into pyqt table, row_data is python list which contains the value of each cell in row.
How to use addTableRow()
We can use it as follow:
self.addTableRow(table, row_1) self.addTableRow(table, row_2) self.addTableRow(table, row_3) self.addTableRow(table, row_4)
Run this code, we will get effect likes: