Connecting Mysql and qt?
Solution 1
Qt provides the model/view framework which is a very flexible tool for presenting data in tables, trees, or lists. so the model you need to use is QSqlTableModel
.
First create a QSqlDatabase instance, and connect to the database
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("my_database");
db.setUserName("username");
db.setPassword("password");
if(!db.open())
QMessageBox::warning(this,"Error","Unable to connect to the database");
then create the model
QSqlTableModel *model = new QSqlTableModel(parent,db);
model->setTable("students");
model->select(); //< fetch data
and finally tell the table to diplay data from this model
QTableView *table = new QTableView;
table->setModel(model);
Solution 2
Under Qt's help system, take a look at Examples, go to SQL, and pick the Table Model Example. You'll find it's not that hard to use MySQL with Qt. (You may have to hand-compile the qtmysql driver; on my system it's in /QtSources/4.7.3/src/plugins/sqldrivers/mysql/mysql.pro. Just qmake/make/make install. Good luck and enjoy!
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I'm having some difficulties connecting a program I'm building with qt. And once I do that, how do I get the database to work with a table widget?
I should probably let you know that I don't know where to begin other than I made the database with libreoffice base.