Задать названия вертикальным заголовкам в QSqlTableModel()
Возникла проблема с названиями вертикальных заголовков в QSqlTableModel(). С горизонтальными заголовками проблем никаких нет. С помощью метода setHeaderData() я задаю названия горизонтальным заголовкам, но с вертикальными это не получается (метод возвращает False). В интернете не могу найти ответ. Код:
import sys
import traceback
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QLabel, QVBoxLayout, QPushButton, QTableView, \
QMessageBox, QDialog, QDialogButtonBox, QLineEdit, QFormLayout
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
def create_table():
createTableQuery = QSqlQuery()
return createTableQuery.exec("""CREATE TABLE IF NOT EXISTS new_contacts (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE
NOT NULL, name VARCHAR(40) NOT NULL, phone VARCHAR(50) NOT NULL)""")
def create_connection(databasename):
connection = QSqlDatabase.addDatabase("QSQLITE")
connection.setDatabaseName(databasename)
if not connection.open():
QMessageBox.warning(None, "RP Contact", f"Database Error: {connection.lastError().text()}")
return False
create_table()
return True
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Window")
self.resize(1000, 600)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.layout = QHBoxLayout()
self.centralWidget.setLayout(self.layout)
self.model = ContactsModel()
self.layout_for_table = QVBoxLayout()
self.layout.addLayout(self.layout_for_table)
self.layout_for_action_button = QVBoxLayout()
self.layout.addLayout(self.layout_for_action_button)
self.table_view = QTableView()
self.layout_for_table.addWidget(self.table_view)
self.button_action1 = QPushButton('Add contact')
self.layout_for_action_button.addWidget(self.button_action1, alignment=Qt.AlignTop)
self.button_action1.clicked.connect(self.open_add_dialog)
self.table_view.setModel(self.model.model)
header = self.table_view.horizontalHeader()
header.setSectionResizeMode(header.ResizeMode.Stretch)
def open_add_dialog(self):
dialog = AddDialog(self)
if dialog.exec() == QDialog.Accepted:
self.model.add_contact(dialog.data)
self.table_view.resizeColumnsToContents()
class ContactsModel:
def __init__(self):
self.model = self._createModel()
def add_contact(self, data):
rows = self.model.rowCount()
self.model.insertRows(rows, 1)
for column, field in enumerate(data):
self.model.setData(self.model.index(rows, column + 1), field)
self.model.submitAll()
self.model.select()
@staticmethod
def _createModel():
tableModel = QSqlTableModel()
tableModel.setTable("new_contacts")
tableModel.setEditStrategy(QSqlTableModel().EditStrategy.OnFieldChange)
tableModel.select()
headers = ("ID", "Name", "Phone")
time = ('08:00', '09:00', '10:00')
for columnIndex, header in enumerate(headers):
tableModel.setHeaderData(columnIndex, Qt.Horizontal, header)
for rowIndex, v_header in enumerate(time):
tableModel.setHeaderData(rowIndex, Qt.Vertical, v_header)
return tableModel
class AddDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle("Add contact")
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.data = None
self.setupUI()
def setupUI(self):
self.nameField = QLineEdit()
self.nameField.setObjectName("Name")
self.phoneField = QLineEdit()
self.phoneField.setObjectName("Phone")
layout = QFormLayout()
layout.addRow("Name:", self.nameField)
layout.addRow("Phone:", self.phoneField)
self.layout.addLayout(layout)
self.buttonsBox = QDialogButtonBox(self)
self.buttonsBox.setOrientation(Qt.Horizontal)
self.buttonsBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.buttonsBox.accepted.connect(self.accept)
self.buttonsBox.rejected.connect(self.reject)
self.layout.addWidget(self.buttonsBox)
def accept(self):
self.data = []
for field in (self.nameField, self.phoneField):
if not field.text():
QMessageBox.critical(self, "Error!", f"You must provide a contact's {field.objectName()}")
self.data = None
return
self.data.append(field.text())
super().accept()
def excepthook(exc_type, exc_value, exc_tb):
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
print("Oбнаружена ошибка !:", tb)
if __name__ == "__main__":
sys.excepthook = excepthook
app = QtWidgets.QApplication(sys.argv)
if not create_connection("new_contacts.sqlite"):
sys.exit(1)
window = MyWindow()
window.show()
sys.exit(app.exec_())