import sys

from PyQt5.QtCore import QSize, Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView

db = QSqlDatabase("QSQLITE")
db.setDatabaseName("chinook.sqlite")
db.open()


class MainWindow(QMainWindow):
	def __init__(self):
		super().__init__()

		self.table = QTableView()

		self.model = QSqlTableModel(db=db)

		self.table.setModel(self.model)

		# tag::sortTable[]
		self.model.setTable("Track")
		# idx = self.model.fieldIndex("Milliseconds")
		# self.model.setSort(idx, Qt.DescendingOrder)
		# self.model.setHeaderData(1, Qt.Horizontal, "Name")
		# self.model.setHeaderData(2, Qt.Horizontal, "Album (ID)")
		# self.model.setHeaderData(3, Qt.Horizontal, "Media Type (ID)")
		# self.model.setHeaderData(4, Qt.Horizontal, "Genre (ID)")
		# self.model.setHeaderData(5, Qt.Horizontal, "Composer")
		
		column_titles = {
			"Name": "Name",
			"AlbumId": "Album (ID)",
			"MediaTypeId": "Media Type (ID)",
			"GenreId": "Genre (ID)",
			"Composer": "Composer",
		}

		for n, t in column_titles.items():
			idx = self.model.fieldIndex(n)
			self.model.setHeaderData(idx, Qt.Horizontal, t)

		self.model.select()
		# end::sortTable[]

		# self.model.setTable("Track")
		# self.model.select()

		self.setMinimumSize(QSize(1024, 600))
		self.setCentralWidget(self.table)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
