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.<br>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. <br>
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 .<br><br>from PyQt4.QtGui import *<br>from PyQt4.QtCore import *<br>from PyQt4.QtSql import *<br>
import sys<br>def createConnection():<br> db=QSqlDatabase.addDatabase("QSQLITE")<br> db.setDatabaseName("test0.db")<br> db.open()<br> <br>def createTable():<br> q=QSqlQuery()<br> q.exec_("create table if not exists t1 (f1 integer primary key,f2 integer)")<br>
q.exec_("delete from t1")<br> q.exec_("insert into t1 values(1,0)")<br> q.exec_("insert into t1 values(2,3)")<br> q.exec_("commit")<br><br> <br>class Model(QSqlTableModel):<br>
def __init__(self,parent):<br> QSqlTableModel.__init__(self,parent)<br> self.setTable("t1")<br> self.select()<br> self.setEditStrategy(QSqlTableModel.OnManualSubmit)<br> self.connect(self,SIGNAL("beforeUpdate(int,QSqlRecord&)"),self.beforeUpdateToTable)<br>
def beforeUpdateToTable(self,row,rec):<br> rec.setValue("f2",999)<br> <br>class TestWidget(QWidget):<br> def __init__(self):<br> QWidget.__init__(self)<br> vbox=QVBoxLayout(self)<br>
self.t=QTableView()<br> self.m=Model(self.t)<br> self.t.setModel(self.m)<br> self.b=QPushButton("submit")<br> vbox.addWidget(self.t)<br> vbox.addWidget(self.b)<br> self.connect(self.b,SIGNAL("clicked()"),self.m.submitAll)<br>
def main():<br> a=QApplication(sys.argv)<br> createConnection()<br> createTable()<br> w=TestWidget()<br> w.show()<br> sys.exit(a.exec_())<br>if __name__=="__main__":<br> main()<br><br>