我正在尝试将QSqlRelationalTableModel
子类化以使用SQLAlchemy,但是在设置数据时遇到了麻烦。
我希望覆盖setData method,但是,我不确定该怎么做。到目前为止,我的课程看起来像:
import sys
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy as sa
from sqlalchemy.orm import class_mapper
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtSql import QSqlTableModel, QSqlRelationalTableModel
from PyQt5.Qt import QVariant, Qt
base = declarative_base()
class SqlAlchemyTableRelationalModel(QSqlRelationalTableModel):
def __init__(self, session, model):
super().__init__()
self.model = model
self.session = session
self.refresh()
def refresh(self):
self.layoutAboutToBeChanged.emit()
self.data = self.session.query(self.model).all()
self.count = len(self.data)
self.columns = attribute_names(self.model)
self.layoutChanged.emit()
def rowCount(self, parent):
'''Overrides QSqlTableModel rowCount
'''
return self.count or 0
def setTable(self):
return self.model.__tablename__
例如,如果我使用简单的User
类进行测试,
class User(base):
__tablename__ = "users"
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String(50))
def __repr__(self):
return f"<User(id={self.id}, name={self.name})>"
带有一些测试数据,
if __name__ == "__main__":
engine = sa.create_engine("sqlite:///my_db.db", echo='debug')
base.metadata.create_all(engine)
DBsession = sa.orm.sessionmaker(bind=engine)
session = DBsession()
# pop some dummy data
if not session.query(User).count():
session.add(User(name="Albert"))
session.add(User(name="Frankie"))
session.add(User(name="Grace"))
session.commit()
model = SqlAlchemyTableRelationalModel(session, User)
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
table = QtWidgets.QTableView(window)
table.setModel(model)
window.show()
sys.exit(app.exec_())
我明白了