Qt SqLite Same Name Different Surname
-
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); mydb = QSqlDatabase::addDatabase("QSQLITE"); mydb.setDatabaseName("C:/sqlite/etudiant.sqlite"); if(!mydb.open()) { qDebug() << "Fail"; } else { QSqlQueryModel *modal = new QSqlQueryModel(); qDebug() << "connected"; QSqlQuery *req = new QSqlQuery(mydb); req->prepare("SELECT name FROM note"); req->exec(); modal->setQuery(*req); ui->comboBox->setModel(modal); } } Widget::~Widget() { delete ui; } void Widget::on_comboBox_currentIndexChanged(const QString &arg1) { QString name = ui->comboBox->currentText(); QSqlQuery qry; qry.prepare("SELECT * FROM note WHERE name = '"+name+"'"); if(qry.exec()) { while (qry.next()) { ui->lineEdit->setText(qry.value(1).toString()); ui->lineEdit_2->setText(qry.value(2).toString()); } } } CREATE TABLE note(id INTEGER PRIMARY KEY, name VARCHAR(25), surname VARCHAR(25)); INSERT INTO note VALUES(1, 'Jhon', 'Samuel'); INSERT INTO note VALUES(2, 'Eddy', 'Ron'); INSERT INTO note VALUES(3, 'Jhon', 'Mark');
well, hello all :p, got a little problem with a tutorial was following, where when the program couldn't display ONLY last name+surname in LineEdit, even when I select the first one in comboBox, just like that:
image1
image2
image3
hope I'll get some help :p to continu my learnings in the good way, thx :) !! -
Hi and welcome to devnet,
Samuel and Mark have the same name, so you'll get two entries with your query. Since you're looping over the result and overwrite the content of lineEdit and lineEdit2, you will only see the value of the last element returned by your query.
On a side note, why are you creating your model's query on the heap ?
-
Don't use a query then. You already have everything at hand through your QComboBox model just modify the original query of the model to retrieve both the name and surname. Your combo box will only show one column.
And then in your function, retrieve the surname again with the model.
-
Yes you can, just change your SQL query to concatenate both.
Since you are using sqlite it should be something like:SELECT name || ' ' || surname as fullname FROM note