Python Forum

Full Version: QTableView set header labels
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
I have a PyQt5 window with a QTableView. The data comes from a XML file. So far everthing works fine.
But now I want to set the header labels because in XML data there is no first line with the labels.
. self.model2 = QStandardItemModel()
. self.model2.setHorizontalHeaderLabels(['ID', 'Datum', 'Gewicht', 'Bmkg'])
. self.tableView.setModel(self.model2)
would do that but I have a own class for column formatting and the 2 can't be combined.
What I have so far:

import sys
import xml.etree.ElementTree as ET
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel
from GewichtUI import Ui_MainWindow    # UI file from Qt Designer


# table format class
# see https://www.pythonguis.com/tutorials/qtableview-modelviews-numpy-pandas/
class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data

    def data(self, index, role):

        if role == Qt.DisplayRole:
            #return self._data[index.row()][index.column()]
            value = self._data[index.row()][index.column()]

            if index.column() == 2:    # Betrag
                return "%.1f" % float(value)
            #elif index.column() == 1:  # Datum
            #    return value.strftime("%Y-%m-%d")
            else:
                return value

        if role == Qt.TextAlignmentRole:
            value = self._data[index.row()][index.column()]

            if index.column() == 0 or index.column() == 2:   # ID, Betrag
                return Qt.AlignmentFlag.AlignVCenter + Qt.AlignmentFlag.AlignRight
            else:
                return Qt.AlignmentFlag.AlignVCenter


    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])



class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        # read XML data
        tree = ET.parse("GewichtDaten.xml")
        root = tree.getroot()
        data = []
        for elem in root:
            datar = []
            for subelem in elem:
                datar.append(subelem.text)
            if len(datar) == 3:
                datar.append("")
            data.append(datar)

        # QTableView
        self.model = TableModel(data)
        self.tableView.setModel(self.model)
        #self.model2 = QStandardItemModel()             # <<<<<<<<  this 3 lines can't be combined with the upper 2 lines
        #self.model2.setHorizontalHeaderLabels(['ID', 'Datum', 'Gewicht', 'Bmkg'])
        #self.tableView.setModel(self.model2)

        self.tableView.verticalHeader().setVisible(False)
        #self.tableView.resizeColumnsToContents()
        self.tableView.setColumnWidth(0,  60)
        self.tableView.setColumnWidth(1, 115)
        self.tableView.setColumnWidth(2,  65)
        self.tableView.setColumnWidth(3, 230)
        self.tableView.scrollToBottom()   # go to last

        # ................

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
        self.tableView.setHorizontalHeaderItem(0, QTableWidgetItem("ID"))
        self.tableView.setHorizontalHeaderItem(1, QTableWidgetItem("Datum"))
        self.tableView.setHorizontalHeaderItem(2, QTableWidgetItem("Gewicht"))
        self.tableView.setHorizontalHeaderItem(3, QTableWidgetItem("Bmkg"))
Oh, sorry this is for QTableWidget.
Problem solfed in table format class:
# table format class
class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data
        #self.rows_nr, self.columns_nr = data.shape
        self.hheaders = ["ID", "Datum", "Gewicht", "Bmkg"]           # <<<<<<<<<<<<<<< NEW LINE

    def data(self, index, role):

        if role == Qt.DisplayRole:
            value = self._data[index.row()][index.column()]

            if index.column() == 2:    # Betrag
                return "%.1f" % float(value)
            #elif index.column() == 1:  # Datum
            #    return value.strftime("%Y-%m-%d")
            else:
                return value

        if role == Qt.TextAlignmentRole:
            value = self._data[index.row()][index.column()]

            if index.column() == 0 or index.column() == 2:   # ID, Betrag
                return Qt.AlignmentFlag.AlignVCenter + Qt.AlignmentFlag.AlignRight
            else:
                return Qt.AlignmentFlag.AlignVCenter


    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])

    def headerData(self, section, orientation, role):           # <<<<<<<<<<<<<<< NEW DEF
        # row and column headers
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.hheaders[section]
        return QtCore.QVariant()