SoFunction
Updated on 2025-04-27

Implementation of QTableView class in PyQt6/PySide6

Implementation of QTableView class in PyQt6/PySide6

Updated: April 27, 2025 11:07:12 Author: Randeng Studio
This article mainly introduces the implementation of the QTableView class in PyQt6/PySide6. The example code is introduced in this article in detail, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.

QTableViewIt is a control used in the PyQt6 or PySide6 library to display two-dimensional tabular data. It is a very powerful and flexible control for displaying and editing table data.QTableViewUsually withQAbstractItemModelSubclasses of  (such asQStandardItemModelor custom model) to provide a data source. I will introduce it in detail belowQTableViewThe main features and how to use them.

1. Basic concepts

  • Table view: Control for displaying two-dimensional tabular data.
  • Model-View ArchitectureQTableViewUse the model-view architecture, whereQTableViewis the view part, responsible for displaying data; and the model (such asQStandardItemModel) is responsible for managing data.
  • Columns and rows: The basic unit in a table, consisting of rows and columns.
  • Cell: A single data item in a table.
  • Select Mode: Controls how the user selects a cell, row, or column.
  • Sort: Support sorting table data.
  • Editing mode: Allows users to edit data directly in the table.

2. Create a QTableView instance

To useQTableView, first you need to import the corresponding library:

from  import QApplication, QTableView, QVBoxLayout, QWidget, QPushButton
from  import QStandardItemModel, QStandardItem
# orfrom  import QApplication, QTableView, QVBoxLayout, QWidget, QPushButton
from  import QStandardItemModel, QStandardItem

Then create a window and add itQTableViewControl:

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        ("My Application")
        (100, 100, 800, 600)
      
        # Initialize the UI        ()
  
    def initUI(self):
        layout = QVBoxLayout()
      
        # Create a table view        self.table_view = QTableView(self)
      
        # Create a model         = QStandardItemModel(4, 3)  #4 rows 3 columns        (['Name', 'age', 'Profession'])
      
        # Add data        (0, 0, QStandardItem('Zhang San'))
        (0, 1, QStandardItem('28'))
        (0, 2, QStandardItem('engineer'))
        (1, 0, QStandardItem('Li Si'))
        (1, 1, QStandardItem('32'))
        (1, 2, QStandardItem('teacher'))
        (2, 0, QStandardItem('Wang Wu'))
        (2, 1, QStandardItem('25'))
        (2, 2, QStandardItem('doctor'))
        (3, 0, QStandardItem('Zhao Liu'))
        (3, 1, QStandardItem('30'))
        (3, 2, QStandardItem('lawyer'))
      
        # Set the model to view        self.table_view.setModel()
      
        # Add button        button = QPushButton("Print Selected", self)
        (self.print_selection)
      
        # Add to layout        (self.table_view)
        (button)
      
        (layout)
  
    def print_selection(self):
        selected_indices = self.table_view.selectedIndexes()
        for index in selected_indices:
            row = ()
            column = ()
            value = ()
            print(f"OK: {row}, List: {column}, value: {value}")

if __name__ == "__main__":
    app = QApplication([])
    window = MyWindow()
    ()
    ()

3. Common properties and methods of QTableView

property

  • model: Get or set the currently used model.
  • selectionModel: Get or set the current selection model.
  • currentIndex: Get or set the currently selected index.
  • horizontalHeader: Get the horizontal table header.
  • verticalHeader: Get the vertical header.
  • cornerButtonEnabled: Get or set whether to enable the corner button.
  • showGrid: Get or set whether to display grid lines.
  • gridStyle: Get or set the grid line style.
  • alternatingRowColors: Get or set whether to alternate row colors.
  • sortingEnabled: Get or set whether to enable sorting.
  • wordWrap: Get or set whether to enable automatic line wrapping.
  • resizeMode: Get or set the resize mode.
  • selectionBehavior: Gets or sets the selection behavior (selects a cell, row, or column).
  • selectionMode: Get or set the selection mode (single or multiple choice).
  • editTriggers: Get or set the edit trigger.
  • toolTip: Get or set tooltip text.
  • statusTip: Get or set the status bar prompt text.

method

  • setModel(QAbstractItemModel): Set the current model used.
  • model() -> QAbstractItemModel: Get the currently used model.
  • setSelectionModel(QItemSelectionModel): Set the current selection model.
  • selectionModel() -> QItemSelectionModel: Get the current selection model.
  • setCurrentIndex(QModelIndex): Set the currently selected index.
  • currentIndex() -> QModelIndex: Get the currently selected index.
  • horizontalHeader() -> QHeaderView: Get the horizontal table header.
  • verticalHeader() -> QHeaderView: Get the vertical header.
  • setCornerButtonEnabled(bool): Set whether to enable the corner button.
  • isCornerButtonEnabled() -> bool: Determine whether the corner button is enabled.
  • setShowGrid(bool): Set whether to display grid lines.
  • showGrid() -> bool: Determine whether grid lines are displayed.
  • setGridStyle(): Set grid line style.
  • gridStyle() -> : Get grid line style.
  • setAlternatingRowColors(bool): Set whether to alternate row colors.
  • alternatingRowColors() -> bool: Determine whether colors alternately.
  • setSortingEnabled(bool): Set whether to enable sorting.
  • isSortingEnabled() -> bool: Determine whether sorting is enabled.
  • setWordWrap(bool): Set whether to enable automatic line wrapping.
  • wordWrap() -> bool: Determine whether to enable automatic line wrapping.
  • setResizeMode(): Set the resize mode.
  • resizeMode() -> : Get the resize mode.
  • setSelectionBehavior(): Set selection behavior.
  • selectionBehavior() -> : Get selection behavior.
  • setSelectionMode(): Set the selection mode.
  • selectionMode() -> : Get the selection mode.
  • setEditTriggers(): Set the edit trigger.
  • editTriggers() -> : Get the edit trigger.
  • setToolTip(str): Set the tooltip text.
  • toolTip() -> str: Get tooltip text.
  • setStatusTip(str): Set the status bar prompt text.
  • statusTip() -> str: Get the status bar prompt text.
  • selectRow(int): Select the specified row.
  • selectColumn(int): Select the specified column.
  • clearSelection(): Clear selection.
  • selectAll():Select all.
  • selectedIndexes() -> List[QModelIndex]: Get all selected indexes.
  • resizeColumnsToContents(): Adjust the column width according to the content.
  • resizeRowsToContents(): Adjust the line height according to the content.
  • hideColumn(int): Hide the specified column.
  • showColumn(int): Displays the specified column.
  • hideRow(int): Hide the specified line.
  • showRow(int): Displays the specified row.

4. Detailed examples

Set up the model

# Create a modelmodel = QStandardItemModel(4, 3)  #4 rows 3 columns(['Name', 'age', 'Profession'])

# Add data(0, 0, QStandardItem('Zhang San'))
(0, 1, QStandardItem('28'))
(0, 2, QStandardItem('engineer'))
(1, 0, QStandardItem('Li Si'))
(1, 1, QStandardItem('32'))
(1, 2, QStandardItem('teacher'))
(2, 0, QStandardItem('Wang Wu'))
(2, 1, QStandardItem('25'))
(2, 2, QStandardItem('doctor'))
(3, 0, QStandardItem('Zhao Liu'))
(3, 1, QStandardItem('30'))
(3, 2, QStandardItem('lawyer'))

# Set the model to viewtable_view.setModel(model)

Get the currently selected index

def print_selection():
    selected_indices = table_view.selectedIndexes()
    for index in selected_indices:
        row = ()
        column = ()
        value = ()
        print(f"OK: {row}, List: {column}, value: {value}")

Select a row or column

# Select Line 1table_view.selectRow(1)

# Select Column 2table_view.selectColumn(2)

Clear Selection

table_view.clearSelection()

Select all

table_view.selectAll()

Adjust column width and row height according to content

table_view.resizeColumnsToContents()
table_view.resizeRowsToContents()

Hide and show columns or rows

# Hide column 2table_view.hideColumn(2)

# Show column 2table_view.showColumn(2)

# Hide Line 3table_view.hideRow(3)

# Show line 3table_view.showRow(3)

Enable or disable sorting

table_view.setSortingEnabled(True)  # Enable sortingtable_view.setSortingEnabled(False)  # Disable sorting

Set selection behavior

table_view.setSelectionBehavior()  # Select the entire linetable_view.setSelectionBehavior()  # Select the entire columntable_view.setSelectionBehavior()  # Select a cell

Set selection mode

table_view.setSelectionMode()  # Single choicetable_view.setSelectionMode()  # Continuous multiple selectionstable_view.setSelectionMode()  # Extended Multiple Choicetable_view.setSelectionMode()  # Multiple choices

Setting up edit triggers

table_view.setEditTriggers( | )  # Double-click or select and click Edit

Setting up tooltips and status bar tips

table_view.setToolTip("This is a table view")
table_view.setStatusTip("View and edit data")

5. Signal and slot mechanism

QTableViewSupports a variety of signals, which can be transmitted during user interaction. Common signals includeclickeddoubleClickedpressedactivatedandselectionChanged. You can handle user input events by connecting these signals to slot functions.

def on_clicked(index):
    row = ()
    column = ()
    value = ()
    print(f"Click: OK: {row}, List: {column}, value: {value}")

def on_double_clicked(index):
    row = ()
    column = ()
    value = ()
    print(f"double click: OK: {row}, List: {column}, value: {value}")

def on_pressed(index):
    row = ()
    column = ()
    value = ()
    print(f"Press: OK: {row}, List: {column}, value: {value}")

def on_activated(index):
    row = ()
    column = ()
    value = ()
    print(f"activation: OK: {row}, List: {column}, value: {value}")

def on_selection_changed(selected, deselected):
    print("Select changes")

table_view.(on_clicked)
table_view.(on_double_clicked)
table_view.(on_pressed)
table_view.(on_activated)
table_view.selectionModel().(on_selection_changed)

6. Custom styles

In addition to using built-in style settings, you can also customize it through stylesheets (QSS).QTableViewAppearance. Stylesheets are similar to CSS and provide powerful style control capabilities.

table_view.setStyleSheet("""
    QTableView {
        background-color: #f0f0f0;
        alternate-background-color: #e0e0e0;
        selection-background-color: #0078d7;
        selection-color: white;
        gridline-color: #cccccc;
        border: 1px solid #cccccc;
    }
    QTableView::item {
        padding: 5px;
    }
    QTableView::item:selected {
        background-color: #0078d7;
        color: white;
    }
    QTableView::item:hover {
        background-color: #d0d0d0;
    }
    QTableView::item:focus {
        outline: none;
    }
    QHeaderView::section {
        background-color: #e0e0e0;
        border: 1px solid #cccccc;
        padding: 5px;
    }
    QHeaderView::section:checked {
        background-color: #0078d7;
        color: white;
    }
""")

7. Dynamic updates and controls

You can update dynamicallyQTableViewcontent, or control its behavior based on certain conditions. For example, update the data of a table when a timer or other event is triggered.

import time
from  import QTimer

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        ("My Application")
        (100, 100, 800, 600)
      
        # Initialize the UI        ()
      
        # Create a timer         = QTimer(self)
        (self.update_table_view)
        (5000)  # Trigger every 5 seconds  
    def initUI(self):
        layout = QVBoxLayout()
      
        # Create a table view        self.table_view = QTableView(self)
      
        # Create a model         = QStandardItemModel(4, 3)  #4 rows 3 columns        (['Name', 'age', 'Profession'])
      
        # Add data        (0, 0, QStandardItem('Zhang San'))
        (0, 1, QStandardItem('28'))
        (0, 2, QStandardItem('engineer'))
        (1, 0, QStandardItem('Li Si'))
        (1, 1, QStandardItem('32'))
        (1, 2, QStandardItem('teacher'))
        (2, 0, QStandardItem('Wang Wu'))
        (2, 1, QStandardItem('25'))
        (2, 2, QStandardItem('doctor'))
        (3, 0, QStandardItem('Zhao Liu'))
        (3, 1, QStandardItem('30'))
        (3, 2, QStandardItem('lawyer'))
      
        # Set the model to view        self.table_view.setModel()
      
        # Add to layout        (self.table_view)
      
        (layout)
  
    def update_table_view(self):
        # Update model data        ()
        (['Name', 'age', 'Profession'])
      
        # Add new data        (0, 0, QStandardItem('Zhang San'))
        (0, 1, QStandardItem('29'))
        (0, 2, QStandardItem('engineer'))
        (1, 0, QStandardItem('Li Si'))
        (1, 1, QStandardItem('33'))
        (1, 2, QStandardItem('teacher'))
        (2, 0, QStandardItem('Wang Wu'))
        (2, 1, QStandardItem('26'))
        (2, 2, QStandardItem('doctor'))
        (3, 0, QStandardItem('Zhao Liu'))
        (3, 1, QStandardItem('31'))
        (3, 2, QStandardItem('lawyer'))

if __name__ == "__main__":
    app = QApplication([])
    window = MyWindow()
    ()
    ()

Summarize

QTableViewIt is a very powerful and flexible control in PyQt6/PySide6, suitable for various scenarios where table data needs to be displayed and edited. By setting different properties and using style sheets, you can create a rich and diverse table view style. At the same time, through the signal and slot mechanism, you can easily handle user input events. I hope the above content can help you better understand and apply itQTableView, and be able to create feature-rich and user-friendly table view controls based on specific needs.

This is the article about the implementation of the QTableView class in PyQt6/PySide6. For more related content of the PySide6 QTableView class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • PySide6
  • QTableView

Related Articles

  • Detailed explanation of transforms module instance in pytorch

    Today, the editor will share with you a detailed explanation of the transforms module example in pytorch, which is of good reference value and hope it will be helpful to everyone. Let's take a look with the editor
    2019-12-12
  • Python implements article plagiarism checking function based on search engine

    This article mainly introduces Python to implement the article plagiarism checking function based on search engines. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.
    2021-05-05
  • Python string definition

    Strings are the most common data type in programs. In Python, there are three ways to define strings. Single, double, and triple quotes.
    2009-09-09
  • Analysis of three roles of commas in Python

    This article mainly introduces the three functions of commas in Python. It analyzes the skills of using commas in Python when converting and printing output. Friends who need it can refer to it.
    2015-06-06
  • Detailed explanation of the python Chinese garbled solution under Linux

    This article mainly introduces the detailed explanation of the gyr code solution in python in Linux. The example code is introduced in this article in detail, which has certain reference value for everyone's study or work. Friends who need it can refer to it.
    2019-08-08
  • Detailed explanation about python class SortedList

    This article mainly introduces a detailed explanation of the SortedList of the python class. It can help you consolidate the basic knowledge of the python class. Friends in need can refer to it for reference. I hope it can be helpful to readers.
    2021-09-09
  • Pprint toss and turns in Python

    This article mainly introduces the pprint toss and tricks in Python. This article focuses on explaining the use of pprint and gives examples of use. Friends who need it can refer to it.
    2015-01-01
  • Python uses Pydub to automatically split audio

    pydub is a lightweight audio processing library that is easy to install and easy to use. Moreover, pydub provides rich audio processing functions, including cutting, merging, conversion, etc. This article will use Pydub to realize the automatic audio segmentation function. Those who are interested can learn about it.
    2023-05-05
  • If judgment statements for basic Python

    Python conditional statements are code blocks that are determined by the execution result (True or False) of one or more statements. The following article mainly introduces relevant information about the basic Python if judgment statements. The article introduces the example code in detail. Friends who need it can refer to it.
    2021-09-09
  • How to connect to Hive using Python 3 on Win10 system

    This article mainly introduces how to connect to Hive using Python 3 on Win10 system, helping everyone better use python to read data, explore, analyze and mine. Interested friends can learn about it
    2020-10-10

Latest Comments