Wait for last character typed in QLineEdit::onTextChanged

c++, qt, qt5

Solution

You will need a timer. Read more about `QTimer` here: http://qt-project.org/doc/qt-5.1/qtcore/qtimer.html

Add a `QTimer *mTimer` as private member variable. Create a slot named for example `do_query` where you will do your query . Put this somewhere in constructor:

mTimer = new QTimer(this); // make a QTimer
mTimer->setSingleShot(true); // it will fire once after it was started
connect(mTimer, &QTimer::timeout, this, &PoS::do_query); // connect it to your slot

Now in your function:

void PoS::on_lineEdit_textEdited()
{
    mTimer->start(100); // This will fire do_query after 100msec. 
    // If user would enter something before it fires, the timer restarts
}

And do your query:

void PoS::do_query()
{
    // your code goes here
}

Problem

I am working on a Point of Sale application, I have a function that takes the text from a QLineEdit (the product's bar code) and runs a query looking for the product to be displayed. The problem is I am running a query every time the text changes, that is, every time a new character is typed. Is there a way to wait for the user to stop typing and then run the query? I will be using a handheld scanner so it would be like 100ms between each character being typed. I think I need something like this: ``` void PoS::on_lineEdit_textEdited() { //check for keys still being pressed //if 100ms have passed without any key press, run query } ``` I have tried to use a timer and also threads (I am very new to Qt 5) but have failed so far.

Original source