c++qtsqliteqt5qsqlquerymodel

Filtering query by QLineEdit and updating QSqlQueryModel


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();

Solution

  • 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);
    }