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.
Practice now: Test your Python skills with interactive challenges
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).
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"))
Practice now: Test your Python skills with interactive challenges
Table in PyQT
The table is defined with the variable data.
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.
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,
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)
Practice now: Test your Python skills with interactive challenges
Practice now: Test your Python skills with interactive challenges