How can I make the header visible in tableView?
import sys
import pandas as pd
from PyQt6.QtWidgets import QTableView, QMainWindow, QApplication
from PyQt6.QtCore import Qt, QAbstractTableModel
from datetime import datetime
from PyQt6 import QtCore
import os
class TableModel(QAbstractTableModel):
def init(self, data):
super().init()
self._data = data
def data(self, index, role):
if role == Qt.ItemDataRole.DisplayRole:
value = self._data.iat[index.row(), index.column()]
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d")
if isinstance(value, float):
return "%.6f" % value
if isinstance(value, str):
return '"%s"' % value
return value
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data.columns)
class MainWindow(QMainWindow):
def init(self):
super().init()
self.table = QTableView()
#self.table.setFixedWidth(500)
aavsoFile = “/home/rpi5/Downloads/AAVSO.txt”
data = self.getDataframe(aavsoFile)
self.model = TableModel(data)
self.table.setModel(self.model)
self.table.resizeRowsToContents()
self.setCentralWidget(self.table)
self.resize_table_to_contents()
def getDataframe(self, aavsoFile):
tmpFile = "tmp.txt"
with open(aavsoFile, "r") as inputFile:
with open(tmpFile, "w") as outputFile:
for line in inputFile:
if not line.strip("\n").startswith("#"):
outputFile.write(line)
data = pd.read_csv(tmpFile, header=None)
data.columns = ['DATE','DIFF','ERR','DETREND_1','DETREND_2']
os.remove(tmpFile)
return data
def resize_table_to_contents(self):
vh = self.table.verticalHeader()
hh = self.table.horizontalHeader()
size = QtCore.QSize(hh.length(), vh.length()) # Get the length of the headers along each axis.
size += QtCore.QSize(vh.size().width(), hh.size().height()) # Add on the lengths from the *other* header
size += QtCore.QSize(20, 20)
self.resize(size)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()