PyQt5: specifying QSqlTableModel
Rich Shepard
rshepard at appl-ecosys.com
Thu Jun 3 15:01:50 BST 2021
Debugging a module to display a QTableView of a small database table I get
this error:
File "activitytypes.py", line 27, in __init__
self.model = qts.QSqlTableModel(dbs.db)
AttributeError: type object 'DBSetup' has no attribute 'db'
My two PyQt5 books and my web searches for using QSql haven't taught me how
to specify the database name in modules that import and use the database
setup module.
Both datasource.py and activitytypes.py are attached and I need to learn how
to use QSql in my database desktop applications. Help's definitely needed
here.
Rich
-------------- next part --------------
# Set up database connection
self.db = qts.QSqlDatabase.addDatabase('QPSQL')
self.db.setDatabaseName('bustrac')
if not self.db.open():
error = self.db.lastError().text()
qtw.QMessageBox.critical(
None, 'DB Connection Error',
'Could not open database file: '
f'{error}')
sys.exit(1)
tables = set('activities','activitytypes','industrytypes',
'locations','organizations','organizations_org_nbr_seq',
'people','people_person_nbr_seq','projects','statustypes')
# Check that all database tables exist
required_tables = {'activities','activitytypes','industrytypes',
'locations','organizations','organizations_org_nbr_seq',
'people','people_person_nbr_seq','projects','statustypes'}
tables = self.db.tables()
missing_tables = required_tables - set(tables)
if missing_tables:
qtw.QMessageBox.critica(
None, 'DB Integrity Error'
'Missing tables, please repair DB: '
f'{missing_tables}')
sys.exit(1)
-------------- next part --------------
import sys
import logging
# bug fix:
from pdb import Pdb; Pdb(skip=['importlib*']).set_trace()
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5 import QtSql as qts
from datasource import DBSetup as dbs
logging.basicConfig(level=logging.DEBUG, filename='activitytypes.log')
#logging.debug('running DBSetup')
#dbs.db
class ATWindow(qtw.QMainWindow):
def __init__(self):
super().__init__()
# Model/View here.
logging.debug('Defining model/view')
self.model = qts.QSqlTableModel(dbs.db) # for single table
self.model.setTable('activitytypes')
self.model.select()
breakpoint()
self.table = qtw.QTableView()
self.table.setModel(self.model)
self.setMinimumSize(qtc.QSize(800, 600))
self.setCentralWidget(self.table)
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
window = ATWindow()
window.show()
#sys.exit(app.exec())
app.exec_()
logging.debug("End of Program")
More information about the PyQt
mailing list