PyQt QTableView Set Horizontal & Vertical Header Labels

The Table/Tree/List Widgets are item-based. The Table/Tree/List Views are View/Model based (sometimes known as MVC, for Model/View/Controller). In the Model/View system, the data is set and manipulated on the model and the view just displays it. To use a View widget, you also have to create a model class. In many cases, people will create their own and subclass from QAbstractItemModel, but you don't have to. Qt provides a non-abstract model you can use with all the view classes - QStandardItemModel.

model = QStandardItemModel()
model.setHorizontalHeaderLabels(['Name', 'Age', 'Sex', 'Add'])
table = QTableView()
table.setModel(model)

There are a couple ways you can do alignment. Alignment data is actually supported in the model, but the header view lets you set a default (I'm guessing it uses that if the alignment data isn't set in the model)

header = table.horizontalHeader()
header.setDefaultAlignment(Qt.AlignHCenter)

To get even more control, you can set the alignment data directly on the model.

# Sets different alignment data just on the first column
model.setHeaderData(0, Qt.Horizontal, Qt.AlignJustify, Qt.TextAlignmentRole)

But the power of the View/Model system is that the view can choose to display that data from the model any way it wants to. If you wanted to create your own custom view, you could have absolute control over how the text in each column is aligned and displayed.


self.tableWidget = QTableView()
projectModel = QSqlQueryModel()
projectModel.setQuery("SELECT * FROM historyDetails where 1")
# projectView = QTableView()
projectModel.setHeaderData(1, Qt.Horizontal, 'Date')
projectModel.setHeaderData(2, Qt.Horizontal, 'Alarm')
self.tableWidget.setModel(projectModel)
self.tableWidget.setColumnHidden(0, True)
# Table will fit the screen horizontally
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.horizontalHeader().setSectionResizeMode(
    QHeaderView.Stretch)

Tags:

Python

Pyqt