2

I got a lineExdit and a tableView i want live update tableView base on typing text in lineEdit.

void updateTableView(QString *st)
{
    QSqlQuery * qry = new QSqlQuery(mydb);

    qry->prepare("select * from Poems where Title like ?%");
    qry->addBindValue(st);
    qry->exec();
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
behruz montazeri
  • 106
  • 2
  • 13
  • You should be updating the model to get it to execute your query and return the result in the tableView. Your table view should have a QSqlQueryModel. – drescherjm Jul 31 '18 at 16:45
  • I already have QSqlQueryModel * modal = new QSqlQueryModel(); ui->tableView->setModel(modal); i don't know how to send the QString st – behruz montazeri Jul 31 '18 at 16:58
  • Just replace the query on the existing model. Don't call `qry->exec();` – drescherjm Jul 31 '18 at 17:02
  • QSqlQueryModel* pModel = dynamic_cast(ui->tableView->model()); if (pModel) { pModel->setQuery(*qry); delete qry;} – drescherjm Jul 31 '18 at 17:05
  • How to use lineEdit with QSqlQueryModel . Should i pass the query string via textChanget method ? Please write the answer with complete code. I'm very novice. – behruz montazeri Jul 31 '18 at 17:16
  • @BehruzMontazeri Test my answer, I have tried to give you a solution, if it does not work then show more detail of your class to be able to adapt it correctly, also do not abuse the dynamic memory. – eyllanesc Jul 31 '18 at 17:22
  • I don't understand please explain the abuse of dynamic memory. Maybe provide me a link to study. – behruz montazeri Jul 31 '18 at 18:21

1 Answers1

3

You are abusing the pointers when it is not necessary, for example the QSqlQuery is creating it using the dynamic memory, and you do not eliminate it, the same with the QString.

Assuming that the QTableView model is a QSqlQueryModel then you should do the following:

...
// constructor
    connect(your_le, &QLineEdit::textChanged, this, &YourClass::updateTableView);
...

void updateTableView(const QString & st)
{
    QSqlQuery query(mydb);
    query.prepare("select * from Poems where Title like ?");
    query.addBindValue(QString("%1%").arg(st));
    query.exec();
    your_QSqlQueryModel->setQuery(query);
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks great help. That works. Which wild card for begging and middle ? – behruz montazeri Jul 31 '18 at 17:47
  • @BehruzMontazeri `%1` belongs to [QString::arg()](http://doc.qt.io/qt-5/qstring.html#arg), and the second is LIKE's own, if my answer helps you do not forget to mark it as correct, if you do not know how to do it review the [tour], that is the best way to thank. – eyllanesc Jul 31 '18 at 17:50
  • 1
    I was going to mention no need for the dynamic allocation of query in my comment on the question. – drescherjm Jul 31 '18 at 17:55