Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt QTableView Set Horizontal & Vertical Header Labels

Tags:

python

pyqt

using QTableWidget i can do

table = QTableWidget()
table.setHorizontalHeaderLabels(QString("Name;Age;Sex;Add").split(";"))
table.horizontalHeaderItem().setTextAlignment(Qt.AlignHCenter)

how can i do same with QTableView ??

like image 811
Ruchit Avatar asked May 14 '16 03:05

Ruchit


2 Answers

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.

like image 193
Brendan Abel Avatar answered Nov 03 '22 16:11

Brendan Abel


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)
like image 1
ranojan Avatar answered Nov 03 '22 15:11

ranojan