Python Forum
QSqlRelationalTableModel: how do I save combobox data?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
QSqlRelationalTableModel: how do I save combobox data?
#1
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.
#!/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.)
Reply
#2
Ok, I have another piece of code (c++ from here 'translated' to python).
Why the combo box is not working? (click previous - next buttons)

#!/usr/bin/env python

from PyQt4 import QtCore, QtGui, QtSql
from PyQt4.QtCore import qDebug
from PyQt4.QtGui import QDataWidgetMapper
from PyQt4.QtGui import QGridLayout
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QWidget
from PyQt4.QtSql import QSqlRelationalDelegate, QSqlTableModel, QSqlRelation, QSqlDatabase, QSqlQuery, QSqlRelationalTableModel



class main(QWidget):

   def __init__(self):
       # Initialize the object as a QWidget
       QWidget.__init__(self)


       self.setupModel()

       self.nameLabel = QtGui.QLabel(("Na&me:"));
       self.nameEdit = QtGui.QLineEdit();
       self.addressLabel = QtGui.QLabel(("&Address:"));
       self.addressEdit =   QtGui.QTextEdit();
       self.typeLabel =  QtGui.QLabel(("&Type:"));
       self.typeComboBox = QtGui.QComboBox();
       self.nextButton = QtGui.QPushButton(("&Next"));
       self.previousButton = QtGui.QPushButton(("&Previous"));

       self.nameLabel.setBuddy(self.nameEdit);
       self.addressLabel.setBuddy(self.addressEdit);
       self.typeLabel.setBuddy(self.typeComboBox);

       relModel = QSqlTableModel(self.model.relationModel(self.typeIndex));
       self.typeComboBox.setModel(relModel);
       self.typeComboBox.setModelColumn(relModel.fieldIndex("description"));

       mapper =    QDataWidgetMapper(self);
       mapper.setModel(self.model);
       mapper.setItemDelegate(QSqlRelationalDelegate(self));
       mapper.addMapping(self.nameEdit, self.model.fieldIndex("name"));
       mapper.addMapping(self.addressEdit, self.model.fieldIndex("address"));
       mapper.addMapping(self.typeComboBox, self.typeIndex);

       self.previousButton.clicked.connect(mapper.toPrevious);
       self.nextButton.clicked.connect(mapper.toNext);
       mapper.currentIndexChanged.connect(self.updateButtons);


       layout =   QGridLayout();
       layout.addWidget(self.nameLabel, 0, 0, 1, 1);
       layout.addWidget(self.nameEdit, 0, 1, 1, 1);
       layout.addWidget(self.previousButton, 0, 2, 1, 1);
       layout.addWidget(self.addressLabel, 1, 0, 1, 1);
       layout.addWidget(self.addressEdit, 1, 1, 2, 1);
       layout.addWidget(self.nextButton, 1, 2, 1, 1);
       layout.addWidget(self.typeLabel, 3, 0, 1, 1);
       layout.addWidget(self.typeComboBox, 3, 1, 1, 1);
       self.setLayout(layout);

       self.setWindowTitle(("SQL Widget Mapper"));
       mapper.toFirst();


   def setupModel(self):
       db = QSqlDatabase.addDatabase("QSQLITE")
       db.setDatabaseName(":memory:")
       if (not db.open()):
           QMessageBox.critical(0, ("Cannot open database"),
                        ("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."), QMessageBox.Cancel);
           return;



       query = QSqlQuery()
       query.exec("create table person (id int primary key, " +     "name varchar(20), address varchar(200), typeid int)")
       query.exec("insert into person values(1, 'Alice', " +    "'<qt>123 Main Street<br/>Market Town</qt>', 101)")
       query.exec("insert into person values(2, 'Bob', "
       "'<qt>PO Box 32<br/>Mail Handling Service"
       "<br/>Service City</qt>', 102)")
       query.exec("insert into person values(3, 'Carol', "
       "'<qt>The Lighthouse<br/>Remote Island</qt>', 103)");
       query.exec("insert into person values(4, 'Donald', "
       "'<qt>47338 Park Avenue<br/>Big City</qt>', 101)");
       query.exec("insert into person values(5, 'Emma', "
       "'<qt>Research Station<br/>Base Camp<br/>"
       "Big Mountain</qt>', 103)");

       query.exec("create table addresstype (id int, description varchar(20))");
       query.exec("insert into addresstype values(101, 'Home')");
       query.exec("insert into addresstype values(102, 'Work')");
       query.exec("insert into addresstype values(103, 'Other')");

       self.model = QSqlRelationalTableModel(self);
       self.model.setTable("person");
       self.model.setEditStrategy(QSqlTableModel.OnManualSubmit);

       self.typeIndex = self.model.fieldIndex("typeid");

       self.model.setRelation(self.typeIndex, QSqlRelation("addresstype", "id", "description"));
       self.model.select();


   def updateButtons(self, row):
       self.previousButton.setEnabled(row > 0)
       self.nextButton.setEnabled(row < self.model.rowCount() - 1);


if __name__ == '__main__':

   import sys

   app = QtGui.QApplication(sys.argv)

   form = main()

   form.show()

   sys.exit(app.exec_())
Reply
#3
This article is dealing with a table widget, but should be similar for other widgets
(one would suspect, although I am not a Qt programmer).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to save to multiple locations during save cubangt 1 509 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  Save data frame to .csv df.to.csv() mcva 1 1,496 Feb-03-2022, 07:05 PM
Last Post: mcva
  SaltStack: MySQL returner save less data into Database table columns xtc14 2 2,113 Jul-02-2021, 02:19 PM
Last Post: xtc14
  How to save json data in a dataframe shantanu97 1 2,121 Apr-15-2021, 02:44 PM
Last Post: klllmmm
  Binding Complex data to Combobox gcfernando 2 2,030 Sep-14-2020, 03:24 PM
Last Post: gcfernando
  sqlite3 database does not save data across restarting the program SheeppOSU 1 3,405 Jul-24-2020, 05:53 AM
Last Post: SheeppOSU
  How to save Python Requests data sent to server? RedLeonard 5 4,795 Jul-05-2020, 10:33 AM
Last Post: RedLeonard
  How to save CSV file data into the Azure Data Lake Storage Gen2 table? Mangesh121 0 2,079 Jun-26-2020, 11:59 AM
Last Post: Mangesh121
  Save Arduino data in mysql server via raspberrypi rithikvg 1 3,347 Jun-24-2020, 10:59 PM
Last Post: Larz60+
  Selection and display of data by combobox LagratteCchouette 10 7,416 Mar-02-2020, 06:34 PM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020