PDA

View Full Version : QSqlTableModel programmatic changes



jtdavidson
8th July 2010, 07:08
I suspect I am thinking about QSqlTableModels in an overly simplistic fashion. (I'm new to both C++ and QT.)

I have a QSqlTableModel, filled with data from an imported CSV file, that I want to write to the database (SQLite).
Before it gets finally written, I give the user a chance to look over what will be written. Then, when they hit IMPORT, I timestamp the records in the tablemodel (the import date is row 5 in the table), and submit them to the database.
Only, my timestamp doesn't work. The records save OK, but without the timestamp.

Here is the code I think is relevant. The model, which has been passed around as a pointer, has an OnManualSubmit edit strategy.

bool BankDB::Import(QSqlTableModel *thisModel)
{
QString importDate = QDate::currentDate().toString("yyyy-MM-dd") + " " + QTime::currentTime().toString("hh:mm:ss");
for (int counter; counter < thisModel->rowCount(); counter ++)
thisModel->record(counter).setValue(5,importDate);
thisModel->submitAll();
}

I also tried using thisModel.record(counter).field(5).setValue(import Date) but to no avail.
I know I can timestamp the records at the time they are parsed from the CSV and added to the tablemodel, but that strikes me as inelegant. I want the stamp right at the last moment, before the submitAll.
What I am missing? You can't just fiddle with tablemodels as if they were 2D arrays before you write them? Or you can't setValue with a QString? It all compiles and runs fine. Just not the way I want it :(
Also, is there a nifty way to a change a field to the same value in a whole tablemodel, without looping through it one record at a time?

thanks in advance

John

jtdavidson
8th July 2010, 07:14
PS, I'd be happy to let SQLite do the timestamping for me, but I can only get it to stamp the date, not the time. It stamps with the correct date but the time set to 00:00:00. Am I doing something wrong there?

the relevant table is created as below. You're looking at field 5, rDate.
"CREATE TABLE Transactions ("
"aName TEXT(20) NOT NULL DEFAULT NULL,"
"tDate Date NOT NULL DEFAULT NULL,"
"tAmount Float NOT NULL DEFAULT 0,"
"tDescription TEXT(100) NOT NULL DEFAULT NULL,"
"aBalance Float NOT NULL DEFAULT 0,"
"rDate Date NOT NULL DEFAULT CURRENT_TIMESTAMP,"
"PRIMARY KEY (aName,tDate,tAmount,tDescription,aBalance),"
"UNIQUE(aName,tDate,tAmount,tDescription,aBalance) ON CONFLICT IGNORE)";

JD2000
8th July 2010, 09:50
try putting


timestamp DATE DEFAULT (datetime('now','localtime')),

in your sqlite schema

jtdavidson
13th July 2010, 03:29
Thanks. In the end I wrote a trigger into the schema that operated as soon as a line was added.
But still I wonder why my first approach didn't work. You can't change a value in a table model before you submit it? Or am I just going about it the wrong way? Do I have to abstract a record model first, or something, rather than accessing tablemodel.record().setvalue ?

John