Showing output of sql query inside a QLabel

2.7k views Asked by At

I am writing a qt gui application where I am planning to show the output of an sql query inside a QLabel.

Now population the output inside a QTableView model is simple enough and that I can do using;

QSqlDatabase dbSqlite = QSqlDatabase::addDatabase("QSQLITE");   //these 2 lines for SQLite DB connection
dbSqlite.setDatabaseName("/home/aj/test.db");
dbSqlite.setUserName("aj");

QString MyQuerySqlite = ui->sqlite_queryEdit->text();    //take the query from a QLineEdit
dbSqlite.open();    //open db connection
QSqlQuery query(MyQuerySqlite,dbSqlite);

if(query.exec())  //populate in table
{
    this->model1=new QSqlQueryModel();
    model1->setQuery(MyQuerySqlite);
    ui->sqlite_tableView->setModel(model1);

    qDebug()<<QDateTime::currentDateTime()<<"SQLITE QUERY SUCCESS "<<dbSqlite.lastError().text();
}

Any idea on how to achieve this inside a QLabel ???

The output of the query will be one single record. For example the name of the world's tallest mountain, or the name of the capital of Engalnd. Just single records.

2

There are 2 answers

0
Nejat On BEST ANSWER

If you want to use QSqlQueryModel for this, you can use QSqlQueryModel::record ( int row ) to retrieve a specific record and then QSqlRecord::value ( int index ) to get a field's value :

QString str = model1->record(0).value(0).toString();
label->setText(str);
0
Jablonski On

You can get result with value method. For example:

QString country;
 QSqlQuery query("SELECT country FROM artist");
 while (query.next()) {
     country.append( query.value(0).toString() + " ");

 }
 label->setText(country);

Also you can read data from model1. Something like:

label->setText(model1->data(model1->index(0,0),Qt::DisplayRole).toString());