Searching word found after several clicks!



  • In my Qt c++ application I have a search function where a word given in a line edit is searched from a table view when the search button is clicked! But the problem is the word which is searched appears on the table view only after the search button is clicked several times!

    following is my code!

    Dialog.h

    ifndef DIALOG_H
    #define DIALOG_H

    #include <QDialog>
    class QSqlQueryModel;
    class QSortFilterProxyModel;
    namespace Ui {
    class Dialog;
    }

    class Dialog : public QDialog
    {
    Q_OBJECT

    public:
    explicit Dialog(QWidget *parent = 0);

    ~Dialog();
    

    private slots:
    void on_searchMessages_clicked();
    void on_pushButton_clicked();

    private:
    Ui::Dialog *ui;
    QSqlQueryModel modal;
    QSortFilterProxyModel
    searchProxy;
    };

    #endif // DIALOG_H

    Dialog.cpp

    #include "dialog.h"
    #include "ui_dialog.h"
    #include <QSqlQuery>
    #include <QSortFilterProxyModel>
    #include <QSqlQueryModel>
    #include "mainwindow.h"
    #include <QSqlDatabase>
    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    ,modal(new QSqlQueryModel(this))
    ,searchProxy(new QSortFilterProxyModel(this))

    {
    ui->setupUi(this);

    }
    Dialog::~Dialog()
    {
    delete ui;
    }

    void Dialog::on_pushButton_clicked()
    {
    {
    if(QSqlDatabase::contains("MyConnection")){

            QSqlQuery qry(QSqlDatabase::database("MyConnection"));
       
            qry.prepare("Select UserName from User");
          
    
            if(!qry.exec()) return;
            modal->setQuery(qry);
          ui->tableView->resizeColumnsToContents();
        }
          QSqlDatabase::database("myconnection").close();
    }
    

    }
    void Dialog::on_searchMessages_clicked()
    {
    searchProxy->setFilterWildcard("" + ui->messageName->text()+ "");
    searchProxy->setSourceModel(modal);
    ui->tableView->setModel(searchProxy);
    }
    }

    How do I correct my code such that the searched word appears from the 1st button click?


  • Moderators

    @Lasith Why do you close database connection in void Dialog::on_pushButton_clicked()?
    Where do you actually open it?



  • @jsulm Sorry It has been commented! :D By the way the specific word I searched is in Row number 1140 in my database table ! To search that I had to click the search button 4 times but when I searched another word which is in in Row number 850 I had to click the search button three times! Is there any relation between the row number and searching? :O


  • Lifetime Qt Champion

    Hi,

    More likely that not all your database data are loaded in memory. You would have to call fetchMore however beware that if you have big tables it's going to cost you more in RAM.



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.