Issue
I’m working on a Python GUI application with PyQt5 which has a QTableView for showing data.
Here is the code:
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
class DataModel(QtCore.QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = []
def data(self, index, role):
if role == Qt.DisplayRole:
return self.data[index.row()][index.column()]
def rowCount(self, index):
return len(self.data)
def columnCount(self, index):
return len(self.data[0])
class MainWindow(UI.UserInterface):
def __init__(self):
super().__init__()
self.model = DataModel()
self.load()
self.TableView.setModel(self.model)
self.TableView.resizeColumnsToContents()
self.TableView.horizontalHeader().setStretchLastSection(True)
def load(self):
try:
self.model.data = [(1, '2020-01-10 00:00:00', 'KANIA', 'HENRYK', 4219)]
except Exception:
pass
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
The class UI.UserInterface
is in separate module. It has the QWidgets of the interface and layout QWidgets. One of them is QTableView
.
I can't seem to find a way to set the header labels for the QTableView
.
I looked for different solutions (some of them below) but none of them worked:
https://doc.qt.io/qt-5/sql-presenting.html (this one is written in C++. I don't quite understand it)
Solution
You must implement headerData()
:
class DataModel(QtCore.QAbstractTableModel):
# ...
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return 'Column {}'.format(section + 1)
return super().headerData(section, orientation, role)
Obviously you can set your own labels even with a simple list containing the labels you want to show.
Note that you should be very careful with naming new attributes to subclasses as they might already exist.
Most importantly, you should not overwrite self.data
.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.