[PyQt] QSqlTableModel and beforeUpdate

Fei Xue xuefey at gmail.com
Thu Sep 10 13:30:29 BST 2009


Hi! This is about QSqlTableModel. I want to modify a field value before it
is written to database,so I connect the QSqlTableModel's beforeUpdate signal
to a class method in which it'll modify a field value.
But when I run this program under PyQt4 4.5.4,it crashed.then I run it under
PyQt4 4.4,it worked without any problem.
Below is the code.Run it and try to click the sumbit button after input
field value,and you will see the result mentioned above .

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtSql import *
import sys
def createConnection():
    db=QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("test0.db")
    db.open()

def createTable():
    q=QSqlQuery()
    q.exec_("create table if not exists t1 (f1 integer primary key,f2
integer)")
    q.exec_("delete from t1")
    q.exec_("insert into t1 values(1,0)")
    q.exec_("insert into t1 values(2,3)")
    q.exec_("commit")


class Model(QSqlTableModel):
    def __init__(self,parent):
        QSqlTableModel.__init__(self,parent)
        self.setTable("t1")
        self.select()
        self.setEditStrategy(QSqlTableModel.OnManualSubmit)

self.connect(self,SIGNAL("beforeUpdate(int,QSqlRecord&)"),self.beforeUpdateToTable)
    def beforeUpdateToTable(self,row,rec):
        rec.setValue("f2",999)

class TestWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        vbox=QVBoxLayout(self)
        self.t=QTableView()
        self.m=Model(self.t)
        self.t.setModel(self.m)
        self.b=QPushButton("submit")
        vbox.addWidget(self.t)
        vbox.addWidget(self.b)
        self.connect(self.b,SIGNAL("clicked()"),self.m.submitAll)
def main():
    a=QApplication(sys.argv)
    createConnection()
    createTable()
    w=TestWidget()
    w.show()
    sys.exit(a.exec_())
if __name__=="__main__":
    main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20090910/719c40cd/attachment.html


More information about the PyQt mailing list