PDA

View Full Version : Qt4 Databases and Model-View problem...



k12yp70n
21st February 2009, 15:14
Hi there folks!

First of all I am a bit of a newbie (both in C++ and in Qt), and I am having a bit of trouble with an application I am writing to manage databases.

the following code is giving me a very bad headache...


void mainwindow::manipdatabase() {
QSqlDatabase *meddb = new QSqlDatabase;
meddb->addDatabase("QMYSQL");
meddb->setHostName ("localhost");
meddb->setDatabaseName ("medadmin");
meddb->setUserName ("medadmin");
meddb->setPassword ("DEEPthoughts1234567890");
if (!meddb->open()) {
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection.\n"
"This program requires MySql to operate. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit."), QMessageBox::Cancel);
}
QSqlTableModel *model = new QSqlTableModel(0, meddb);
model->setTable ("test");
model->setEditStrategy (QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Surname"));

ui->View->setWindowTitle ("Patients List");
ui->View->setModel (model);
ui->View->setSelectionBehavior (QAbstractItemView::SelectRows);
ui->View->setSelectionMode (QTableView::SingleSelection);
ui->View->setVisible (true);
}

It complains about the line were the model is declared according to qmake "expected QObject", but shouldn't that set the parent widget to none (and therefore work)???

My apologies for being such a newbie, I hope that any of you could please help me (if you want you can always write a little line of code explaining how it should be done).

Thank you in advance,

:D

wysota
21st February 2009, 15:39
You use QSqlDatabase incorrectly.

You should do it like this:

QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("acidalia");
db.setDatabaseName("customdb");
db.setUserName("mojito");
db.setPassword("J0a1m8");
bool ok = db.open();

As for the error - the model constructor awaits an object but you are giving it a pointer. I suggest you don't give the second argument at all, it's optional and if you initialize the database object properly, the model will pick it up and work on it.

k12yp70n
21st February 2009, 16:01
Thank you very much for your help! :D

If it wasn't for you I probably would have never got there by myself!

If it wouldn't be way too troublesome I would also like to ask a little question: the table view shows up completely blank, is there anything I need to do to at least have the column headers showing up???????

And once more, thank you.
:D

wysota
21st February 2009, 21:19
Yes, you need to set a model on the table. Instead of a table view you can use a table widget and tell it how many columns it should have. That should be enough to get the horizontal header.