Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Rocking MVC with PySide & Qt in my editable transactions form!
import sys
import os
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSql import *
class QtDbSession:
# Set up the database connection
def __init__(self,db_path,db_name):
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName(os.path.join(db_path,db_name))
self.db.open()
def close(self):
self.db.close()
class MyModel(QSqlRelationalTableModel):
# **** THE MODEL ******
# Here's the source of the magic: the QSqlRelationalTableModel!
# For the first time, I'm reading AND writing data in a Sqlite table without a single line of SQL!
def __init__(self, parent, *args):
QSqlRelationalTableModel.__init__(self, parent, *args)
self.setTable('transactions')
self.setEditStrategy(QSqlRelationalTableModel.OnManualSubmit)
# Column 4 in 'transactions' = 'Category', which is the ID number. Set it to the description in 'accounts'
self.setRelation(4,QSqlRelation('accounts','AccountNum','AccountDescription'))
# Column 7 in 'transactions' = 'Account', also an ID number. Same setup as above.
self.setRelation(7,QSqlRelation('accounts','AccountNum','AccountDescription'))
self.select()
class MyView(QTableView):
# **** THE VIEW ******
def __init__(self, title, model, *args):
QTableView.__init__(self,*args)
self.setModel(model)
self.setItemDelegate(QSqlRelationalDelegate(self))
self.setWindowTitle(title)
# ..AND LAST BUT NOT LEAST... **** THE CONTROLLER ! ****
if __name__== '__main__':
app = QApplication([])
session = QtDbSession("D:\Dropbox\projects\dataq","dataq.db")
model = MyModel(None)
view = MyView('Transactions Form',model)
view.show()
app.exec_()
# Commit all the data changes made in the model to the database.
model.submitAll()
session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment