Displaying the output of a sql query inside a QLabel

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

Now the collection of results inside the QTableView model is simple enough that I can use,

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 in QLabel ???

The result of the query will be one separate record. For example, the name of the highest mountain in the world or the name of the capital of Engald. Selected entries only.

+3


source to share


2 answers


If you want to use QSqlQueryModel

for this, you can use QSqlQueryModel::record ( int row )

to get a specific record and then QSqlRecord::value ( int index )

to get the value of a field:



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

      

+3


source


You can get the result using the 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());

      

+2


source







All Articles