📜  python set table widget header - Python (1)

📅  最后修改于: 2023-12-03 15:34:04.304000             🧑  作者: Mango

Python Set Table Widget Header

In Python, you can use the QTableWidget class of the PyQt5 library to create Table Widgets in your GUI application. A Table Widget is a user interface element that displays data as a table.

The QTableWidget class allows you to set the header labels of your Table Widget by using the setHorizontalHeaderLabels() method. This method takes a list or tuple of strings as its argument.

Here's an example code snippet to create a table widget with header in Python:

from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem

table = QTableWidget()
table.setColumnCount(3)
table.setRowCount(2)
header_labels = ('Name', 'Age', 'Gender')
table.setHorizontalHeaderLabels(header_labels)

# Insert data to cells
table.setItem(0, 0, QTableWidgetItem('John'))
table.setItem(0, 1, QTableWidgetItem('30'))
table.setItem(0, 2, QTableWidgetItem('Male'))
table.setItem(1, 0, QTableWidgetItem('Jenny'))
table.setItem(1, 1, QTableWidgetItem('25'))
table.setItem(1, 2, QTableWidgetItem('Female'))

In the above code, we have created a table widget instance and set the number of columns and rows using setColumnCount() and setRowCount() methods respectively. Then, we set the header labels by passing a tuple of strings to setHorizontalHeaderLabels() method. Finally, we insert data into the table cells using the setItem() method.

You can customize the appearance of your header by using the horizontalHeader() method and adjusting its properties such as font size, background color, etc.

I hope this article helps you in creating table widgets with headers in your Python application.