PyQt5 - QTableWidget

PyQt5 - QTableWidget

The QTableWidget class in PyQt5 is a widget that provides a table view to manage data in a grid format. It is an item-based table view with a default model.

Below are some basic operations and features of QTableWidget:

  • Create a QTableWidget:
table = QTableWidget() 
  • Set Rows and Columns:
table.setRowCount(5) table.setColumnCount(3) 
  • Set Headers:
table.setHorizontalHeaderLabels(['Header 1', 'Header 2', 'Header 3']) 
  • Add Items:
table.setItem(0, 0, QTableWidgetItem("Item (1,1)")) table.setItem(0, 1, QTableWidgetItem("Item (1,2)")) 
  • Resize Columns and Rows to Contents:
table.resizeColumnsToContents() table.resizeRowsToContents() 
  • Retrieve Selected Items:
selected_items = table.selectedItems() 
  • Add a Vertical Scroll Bar:
table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) 
  • Enable Sorting:
table.setSortingEnabled(True) 

Let's create a simple PyQt5 application to demonstrate the use of QTableWidget:

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget class TableDemo(QMainWindow): def __init__(self): super().__init__() # Create a QTableWidget self.table = QTableWidget(self) # Set number of rows and columns self.table.setRowCount(5) self.table.setColumnCount(3) # Set headers self.table.setHorizontalHeaderLabels(['Header 1', 'Header 2', 'Header 3']) # Populate the table with data for row in range(5): for col in range(3): self.table.setItem(row, col, QTableWidgetItem(f"Item ({row+1}, {col+1})")) # Layout setup layout = QVBoxLayout() layout.addWidget(self.table) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) # Window properties self.setWindowTitle("QTableWidget Demo") self.resize(400, 300) if __name__ == '__main__': app = QApplication(sys.argv) window = TableDemo() window.show() sys.exit(app.exec_()) 

When you run the above code, you'll see a simple table with headers and some populated data. This is a basic example; you can further customize the QTableWidget to suit your needs, add context menus, handle different events, and more.


More Tags

jackson process bluetooth cocoa-touch ssis qgis gawk svg.js scheduling air

More Programming Guides

Other Guides

More Programming Examples