Hi,
first thank for this book and clear examples, I learnt a lot!
I try to code a window to load data from a *txt file and preview it into a TableView (after to select, using combobox, some row and column as headers containing data on which to perform analyses).
How to display into the example of TableView from your TableModel you provide p.295 a table that has some row and column of different sizes / number of elements?
What I naively tried:
1- calculate the max number of columns in the file, then send to columnCount this max number for every column
2- and add a test if element is void, and return a string with a space or another char
But it doesn’t work, and I don’t understand how this Tablemodel works to succeed. I think solution is in indexing row and column but still don’t understand how this class does that?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QFileDialog, QTextEdit, QPushButton, QLabel, QVBoxLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QDir
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
self.maxcolumn = max([len(i) for i in self._data])
def data(self, index, role):
if role == Qt.TextAlignmentRole:
return Qt.AlignCenter
if role == Qt.DisplayRole:
if not self._data[index.row()][index.column()]:
print("sad!")
return " "
else:
value = self._data[index.row()][index.column()]
if isinstance(value, float):
return "%.2f" % value
return value
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return self.maxcolumn
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.data1 = []
self.button = QPushButton('Upload data')
self.button.clicked.connect(self.get_text_file)
self.table = QtWidgets.QTableView()
layout = QVBoxLayout()
layout.addWidget(self.table)
layout.addWidget(self.button)
self.setLayout(layout)
def get_text_file(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.AnyFile)
dialog.setFilter(QDir.Files)
if dialog.exec_():
file_name = dialog.selectedFiles()
if file_name[0].endswith('.txt'):
with open(file_name[0], 'r') as f:
self.data1 = f.readlines()
for x in range(len(self.data1)) :
a = self.data1[x]
b = a.split()
self.data1[x] = b
self.model = TableModel(self.data1)
self.table.setModel(self.model)
f.close()
else:
pass
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())