Feb-08-2017, 03:37 PM
If you run this code, a database is created, and a window opens, where you can select (on the right) a client from a list (combobox) of clients.
How do I save it in the database?
(it has something to do with model.setData or something.)
#!/usr/bin/env python
from PyQt4 import QtCore, QtGui, QtSql
def initializeModel(model):
model.setTable('devices')
model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
model.setRelation(2, QtSql.QSqlRelation('clients', 'id', 'lastname'))
model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
model.setHeaderData(1, QtCore.Qt.Horizontal, "Brand")
model.setHeaderData(2, QtCore.Qt.Horizontal, "Client")
model.select()
def createView(title, model):
view = QtGui.QTableView()
view.setModel(model)
view.setItemDelegate(QtSql.QSqlRelationalDelegate(view))
view.setWindowTitle(title)
return view
def createDB():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('rd.db')
if not db.open():
QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
QtGui.qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n" "Click Cancel to exit."),
QtGui.QMessageBox.Cancel)
return False
query = QtSql.QSqlQuery()
query.exec_("create table devices(id int primary key, "
"brand varchar(20), client_id int)")
query.exec_("insert into devices values(101, 'Toshiba', 17)")
query.exec_("insert into devices values(102, 'LG', 14)")
query.exec_("insert into devices values(103, 'Sony', 16)")
query.exec_("create table clients(id int primary key, "
"firstname varchar(20), lastname varchar(20))")
query.exec_("insert into clients values(14, 'John', 'Padd')")
query.exec_("insert into clients values(15, 'Bob', 'New')")
query.exec_("insert into clients values(16, 'Sean', 'Wheeler')")
query.exec_("insert into clients values(17, 'Diana', 'Rash')")
query.exec_("insert into clients values(18, 'George', 'Nett')")
return True
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
createDB()
model = QtSql.QSqlRelationalTableModel()
initializeModel(model)
view = createView("Relational Table Model", model)
view.show()
sys.exit(app.exec_())My question is, ok I have selected one of the clients in the list of the combobox.How do I save it in the database?
(it has something to do with model.setData or something.)
