Day 24 | day 28 learn PyQt5, QTableView of advanced controls

Keywords: Python Data Analysis PyQt5

Advanced component does not mean how "advanced" the component is, but means powerful. If you want to realize a fully functional table function, it may take several days to write a lot of code. You can call the wx.Grid component directly and do it in three or two times, so this component is very advanced.

Common advanced components of PyQt5 include table view control QTableView, QTableWidget and list view QList

View and QListWidget, tree structure QTreeWidget and label view QTabWidget.

The table view control QTableView needs to be used with the data model. The data model of the table needs to fill in the data of each row and column, just like the execl table.

QTableView is designed based on MVC mode. M(Model) is the data model, V(view) is the QTableView View, which is used to display the data model, and C (controller) is the controller, which is combined with View. Bind the data source through the setModel() method. The common methods are as follows:



setSpan(int, int, int, int)

Merge rows and columns. The four parameters are start row, start column, number of merged rows and list;


Clear all merged cells (cancel merging);


Value is
When QAbstractItemView.SelectRows is selected, it will select by row instead of all rows in the default optional;


Value is
When QAbstractItemView.SingleSelection, it will select by cell instead of all rows in the default optional;


When the value is QTableView.NoEditTriggers, set the cell as non editable;

hideColumn(int column)

Hide the specified column;

showColumn(int column)

Displays the specified column;

hideRow(int row)

Hide the specified row;

showRow(int row)

Displays the specified row;


Returns the horizontal header object. When setSectionResizeMode(QHeaderView.Stretch) is called, all columns are evenly distributed; When setStretchLastSection(True) is called, the last column is automatically stretched.

isColumnHidden(int column)

Returns a bool value indicating whether the column is hidden;

isRowHidden(int row)

Returns a bool value indicating whether the row is hidden;

resizeColumnToContents(int column)

Adjust the column width of the specified column according to the content. Column is the subscript of the column, starting from 0;


Adjust the column width of all columns according to the content;

resizeRowToContents(int row)

Adjust the row height of the specified row according to the content. Row is the subscript of the row, starting from 0;


Adjust the row height of all rows according to the content;

sortByColumn(int column,

SortOrder order)

Sort column s. The sorting method is specified by order. Qt.descending order is in descending order and Qt.AscendingOrder is in ascending order;


Bind model data.

The model data that the table view control QTableView can bind is shown in the following table:

Model name



Store a set of strings;


Storing data of any hierarchy;


Encapsulate the file system;


Encapsulate the query result set of SQL;


Encapsulate tables in SQL;


Encapsulate the SQL table with foreign key.

The common methods of the model are shown in the table below:



setHorizontalHeaderLabels([str] labels)

Used to set the text displayed in multiple sections of the horizontal header in sequence at one time. This method has no return value. A section with a label set will automatically create the item corresponding to the section;

setVerticalHeaderLabels([str] labels)

Used to set the text displayed in multiple sections of the vertical header in sequence at one time. This method has no return value. A section with a label set will automatically create the item corresponding to the section;


Add item to the template;


Add QStandItem data;


int column)

Find data in the specified column and return List;

removeRows(int row)

Delete the data of the specified row;

data(QModelIndex index)

Get the value of the cell;


Obtain the total number of columns;

Program list:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget,
  QHBoxLayout, QTableView, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem, 
  QBrush, QColor
from PyQt5.QtCore import Qt

# Inherit QWidget
class TableViewWidget(QWidget):
    customer_list = [("Zhang San", "male", "1981-06-02", "13888888888",
                      "No. 999, No. 9 near Penguin House, Antarctica Road"),
                     ("Li Si", "male", "1988-08-08", "13999999999",
                      "666, No. 6, downhill road, polar bear store"),
                     ("Li Qingzhao", "female", "1986-06-06", "13666666666",
                      "888 Road, No. 8, Miaowan Road, ancient poetry, Qinling")]
    itemModel = None

    def __init__(self):

    def init_ui(self):
        # Set layout
        layout = QHBoxLayout()
        table_view = QTableView(self)
        # Data hierarchy, 10 rows and 5 columns
        self.itemModel = QStandardItemModel(10, 5)
        # Header
        self.itemModel.setHorizontalHeaderLabels(["full name", "Gender", "birthday", 
                                                  "cell-phone number", "address"])
        # Input content
        for (row, customer) in enumerate(self.customer_list):
            for column in range(len(customer)):
                self.itemModel.setItem(row, column, 
        # Bind data source
        # Last column auto stretch
        items = self.itemModel.findItems("13666666666", 
                                         Qt.MatchExactly, 3)
        # Set the back color of the cell to red
        if len(items) > 0:
            items[0].setForeground(QBrush(QColor(255, 0, 0)))
        # Merge rows and columns
        table_view.setSpan(0, 1, 2, 1)
        # Cells are not editable
        # Select single line
        # Click event
        # Double click the event
        # resize window
        self.resize(900, 500)
        # Center window
        # Window title
        self.setWindowTitle("Table application")
        # Display window
        # Get folder path

    def table_click(self, model_index):
        # Subscripts of selected rows and columns
        row = model_index.row()
        column = model_index.column()
        item = self.itemModel.index(row, column).data()
        print("The value of the selected cell:%s" % item)
        # The value of the selected cell
        column_data =
        print("The value of the selected cell:%s" % column_data)
        # Total number of columns
        column_count = self.itemModel.columnCount()
        for i in range(column_count):
            # Get the value in the cell according to the row and column
            item = self.itemModel.index(row, i).data()
            print(item, end=" ")

    def double_click(self, model_index):
        # The value of the selected cell
        column_data =

    # Achieve centering
    def center(self):
        f = self.frameGeometry()
        c = QDesktopWidget().availableGeometry().center()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = TableViewWidget()

After running the program, the pop-up window is as follows:

Well, that's all for QTableView. Pay attention to me. The next section is more exciting.

Today's headline: Lao Chen said that Python will be fully shared by 2021 national day. The complete courses include:
1. 12 days
2. Data analysis in 16 days
3. Python web crawler in 10 days
four   Django3.0 project practice
five   Wxpython in 25 days
six   The 28 day society PyQt5 is being released
seven   The 25 day society Seaborn data analysis was released on csdn
eight   "3-day Pyecharts data analysis" was released during the national day

Posted by grandadevans on Sat, 02 Oct 2021 15:54:11 -0700