from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtQuick import QQuickView
class MyTableModel(QAbstractTableModel):
def __init__(self, data, header_data=None, parent=None):
super().__init__(parent)
self._data = data
self._header_data = header_data if header_data else [f"Column {i+1}" for i in range(len(data[0]))] if data else []
def rowCount(self, parent=None):
return len(self._data)
def columnCount(self, parent=None):
if self._data:
return len(self._data[0])
return 0
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
return self._data[row][col]
elif role == Qt.BackgroundRole:
if row % 2 == 0:
return QColor(240, 240, 240)
else:
return QColor(255, 255, 255)
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
if section < len(self._header_data):
return self._header_data[section]
return None
# Sample Data
data = [
["Alice", 25, "New York"],
["Bob", 30, "London"],
["Charlie", 28, "Paris"],
["David", 35, "Tokyo"]
]
header_data = ["Name", "Age", "City"]
# Create the model
model = MyTableModel(data, header_data)
# QML code
qml_code = """
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 600
height: 400
TableView {
width: parent.width
height: parent.height
model: myModel
TableViewColumn {
role: "Name"
title: "Name"
width: 100
}
TableViewColumn {
role: "Age"
title: "Age"
width: 50
}
TableViewColumn {
role: "City"
title: "City"
width: 100
}
headerDelegate: Rectangle {
width: 100
height: 25
color: "lightblue"
Text {
rotation: -90
text: model.headerData(section, Qt.Horizontal, Qt.DisplayRole)
anchors.centerIn: parent
}
}
}
}
"""
# Create the QML engine
engine = QQmlApplicationEngine()
# Set the model as a context property
engine.rootContext().setContextProperty("myModel", model)
# Load the QML code
engine.loadData(qml_code.encode())
# Get the root object
root = engine.rootObjects()[0]
# Show the window
root.show()
# Run the application
app = QApplication([])
app.exec_()
Explanation:
-
MyTableModel Class: This class inherits from QAbstractTableModel and provides the data and header information for the table view.
-
QML Code: The QML code defines a TableView with three columns and a custom headerDelegate that rotates the header text by 90 degrees.
-
QQmlApplicationEngine: This class is used to load and run the QML code. The MyTableModel instance is set as a context property so that it can be accessed from the QML code.
-
Running the Application: The QML code is loaded into the QQmlApplicationEngine, and the root object (the ApplicationWindow) is shown. The application event loop is then started with app.exec_().
This approach allows you to use QML to create a table view with a custom horizontal header, while still using a Python-based model derived from QAbstractTableModel.