PDA

View Full Version : QSqlQueryModel edit table & direct query to the database



TomASS
1st October 2011, 21:47
Hello all!

I've started developing my programs using MVC. I've:


model = new QSqlQueryModel;
model->setQuery("SELECT ID_t, ID_podmiot FROM m_transporty LIMIT 0 , 30");
if(model->lastError().isValid())
qDebug() << model->lastError();

ui->tableView->setModel(model);

Works beautifully!

Now - how do I now edit a data (eg in the "line" table)? How to call a cell editing (I click on it and nothing happens), and later as the values ​​(for example, when you click "save") write to the database?
I know I can read all the data in the model, but probably not the point of MVC. Since I changed one record (row) is what I overexpose the entire model?


Can I implement editing only in the model?
How do I add or delete a record not only the model but also from the database?

Thanks!

cincirin
2nd October 2011, 08:50
The model is read-only by default. To make it read-write, you must subclass it and reimplement setData() and flags().
Another option is to use QSqlTableModel, which provides a read-write model based on a single database table.


See query model example (http://doc.qt.nokia.com/latest/sql-querymodel.html)

TomASS
2nd October 2011, 13:45
Thanks!
That what I'm saing!


Allmost ;)

I'ld like to excecute any query, so I've:

model = new EditableSqlModel;
model->setQuery("SELECT ID_t, ID_podmiot, ID_oddzial, Numer, Numer_zleceniodawcy FROM m_transporty LIMIT 0 , 30");
but in example there is:


void EditableSqlModel::refresh()
{
setQuery("select * from person");
setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));
}

I'd like to change query in setQuery automatyicly. I've tried use to

setQuery(this->query().executedQuery());
but it's empty :(

cincirin
3rd October 2011, 08:08
I'd like to change query in setQuery automatyicly.
Can you be a little more explicit? If you need to change query in model view, you will always have to call
QSqlQueryModel::setQuery (and also to set header data in model)