Tables can be created with the QTableWidget. It is an item-based table view, similar to what you would see in Excel.

You can include the table widget as part of your gui, or popup a window with an excel like table.

In this example (PyQt5) it’ll show a window with the table, but you can make it part of your window gui with designer.

Related Course:
PyQt Desktop Apps with Python
icon

Tables

QTableWidget

The QTableWidget is a table widget with rows and columns.

The object has the methods .setRowCount(x) and .setColumnCount(y), where x is number of rows and y number of columns. You could use this as self.setRowCount(5).

pyqt table

The contents is set with self.setItem(m, n, newitem), where m and n is the coordinate inside the table.

The variable newitem is of type QTableWidgetItem, which can take a text value as string. For instance: .setItem(1,2, QTableWidgetItem("Table Cell"))

Related Course:
PyQt Desktop Apps with Python
icon

Table in PyQT

The table is defined with the variable data.

1
2
3
data = {'col1':['1','2','3','4'],
'col2':['1','2','1','3'],
'col3':['1','1','2','1']}

The example below creates a table with 3 columns and a number of rows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
     
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import sys

data = {'col1':['1','2','3','4'],
'col2':['1','2','1','3'],
'col3':['1','1','2','1']}

class TableView(QTableWidget):
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.setData()
self.resizeColumnsToContents()
self.resizeRowsToContents()

def setData(self):
horHeaders = []
for n, key in enumerate(sorted(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)

def main(args):
app = QApplication(args)
table = TableView(data, 4, 3)
table.show()
sys.exit(app.exec_())

if __name__=="__main__":
main(sys.argv)