Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Delay action to wait for user interaction: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Remove non-functioning "toc" command)
(fix variable name (typo in previous edit))
 
(5 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
{{LangSwitch}}
 
[[Category:Snippets]]
 
 
= Delay action to wait for more user input =
 
== Usecase ==
== Usecase ==


Have you ever created a text filter that can be used to filter a (big) item view so users can get to their content faster? If you did, you probably simply connected <code>QLineEdit::textChanged ( const QString & text ) </code> to a <code>QSortFilterProxyModel::setFilterXXX </code> method, either via your own slot to add some wildcards or wrap the line edit's string in a regular expression or not. The problem is, now each character typed by the user triggers an update of the whole view, and the proxy model has to go through all the items in your list over and over again. That could get expensive and slow, thereby instead of improving user experience you actually annoy the user…
Have you ever created a text filter that can be used to filter a (big) list of items? If you did, you probably simply connected <code>QLineEdit::textChanged ( const QString & text ) </code> to a method like <code>YourClass::filterEntries( const QString & filterText )</code> The problem is, now each character typed by the user triggers an update of the whole view, and the class has to go through all the items in your list over and over again. That could get expensive and slow, thereby instead of improving the user experience, you actually annoy the user.


There are many such cases where events can happen in quick succession, and you'd like your application to respond to these changes. On the one hand, it makes sense to respond to as many of those events in one go as possible, but on the other hand you don't want the update to take too much time after the user is done typing his filter string (or whatever it is you are waiting for).
There are many such cases where events can happen in quick succession, and you'd like your application to respond to these changes. On the one hand, it makes sense to respond to as many of those events in one go as possible, but on the other hand you don't want the update to take too much time after the user is done typing their filter string (or whatever it is you are waiting for).


== Enter DelayedExecutionTimer ==
== Solution ==


One solution to this problem is to use two timers, one short enough so an update will still appear snappy but long enough that it will probably not trigger before there is more input (for instance, if the user is not done typing his filter), and one longer timer that will trigger a set time after the first event happened, so the update will not be delayed forever as more and more events happen that would otherwise delay the update.
The simplest solution to this problem is to use a {{class|QTimer}}. This allows you to, for instance, implement a text filter that waits for the user to stop typing and then run the query. Below is example code that shows how to implement this:
 
The <code>DelayedExecutionTimer</code> class implements this approach, making it very easy to apply in all such cases without mucking about with creating, setting and resetting timers for each case where you need this. <code>DelayedExecutionTimer</code> basically provides one slot <code>trigger()</code> and one signal <code>triggered()</code>. Instead of directly connecting the event to the action (connecting the <code>textChanged()</code> to the <code>setFilter()</code>, for instance), you connect the <code>QLineEdit::textChanged()</code> to <code>DelayedExecutionTimer::trigger()</code>, and <code>DelayedExecutionTimer::triggered()</code> to <code>QSortFilterProxyModel::setFilter…()</code>.
 
<code>DelayedExecutionTimer</code> also provides two more versions of both the trigger() slot and the triggered() signal for convenience. These allow to pass a QString or an int as an argument. The triggered() signal will be emitted without argument, and with both a QString and with an int argument, carrying the last value that was passed in by the corresponding trigger() signal (or a default value if no such value was set). As a last convenience feature, you can set pre- and post- strings, that will be added to the string value before the signal is send. This way, connecting the line edit to the <code>SortFilterProxy</code> model becomes as simple as this:


First, add a <tt>{{class|QTimer}} *m_typingTimer</tt>, and a <tt>{{class|QString}} m_filterText</tt> as private member variables for the class.
Initialize the QTimer in the class constructor:
<code>
<code>
// m_proxy is a QSortFilterProxyModel pointer
m_typingTimer = new QTimer( this );
// m_ui->leFilter is a QLineEdit representing the filter string to use
m_typingTimer->setSingleShot( true ); // Ensure the timer will fire only once after it was started
 
DelayedExecutionTimer* filterDelay = new DelayedExecutionTimer(this);
filterDelay->setStringPreFix("'''");
filterDelay->setStringPostFix("'''");
connect(m_ui->leFilter, SIGNAL (textChanged(QString)), filterDelay, SLOT (trigger(QString)));
connect(filterDelay, SIGNAL (triggered(QString)), m_proxy, SLOT (setFilterWildcard(QString)));
 
</code>
</code>


That's all. Of course, you can tweak the timings by either passing in a reasonable minimum and maximum delay in the constructor, or using the setters for these.
Then, create a slot where the query will be performed, and connect the timer to it:
 
== Code ==
 
=== delayedexecutiontimer.h ===
 
<code>
<code>
/*
connect( m_typingTimer, &QTimer::timeout, this, &YourClass::filterEntries );
Copyright © 2011, Andre Somers
All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS AND/OR RATHENAU INSTITUTE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DELAYEDEXECUTIONTIMER_H
#define DELAYEDEXECUTIONTIMER_H
 
#include <QObject>
class QTimer;


/'''*
void YourClass::filterEntries()
Class to delay execution an action in response to events that may come in bursts
*/
class DelayedExecutionTimer : public QObject
{
{
Q_OBJECT
    // The actual filtering code goes here, using the string stored in the m_filterText class variable
public:
}
DelayedExecutionTimer(int maximumDelay = 1000, int minimumDelay = 250, QObject''' parent = 0);
DelayedExecutionTimer(QObject* parent);
 
/**
The minimum delay is the time the class will wait after being triggered before
emitting the triggered() signals.
*/
void setMinimumDelay(int delay) {m_minimumDelay = delay;}
int minimumDelay() const {return m_minimumDelay;}
/'''*
The maximum delay is the maximum time that will pass before a call to the trigger() slot
leads to a triggered() signal.
*/
void setMaximumDelay(int delay) {m_maximumDelay = delay;}
int maximumDelay() const {return m_maximumDelay;}
 
/'''*
Sets a string to be attached to the end of the last string set using trigger(QString)
in the triggered(QString) signal. This is useful for, for instance, appending wildcard
characters to a filter string.
*/
void setStringPostfix(const QString& postfix) {m_postfix = postfix;}
/'''*
Sets a string to be prepended to the beginning of the last string set using trigger(QString)
in the triggered(QString) signal. This is useful for, for instance, appending wildcard
characters to a filter string.
*/
void setStringPrefix(const QString& prefix) {m_prefix = prefix;}
 
signals:
void triggered();
void triggered(QString);
void triggered(int);
 
public slots:
void trigger();
void trigger(QString);
void trigger(int);
 
private slots:
void timeout();
 
private:
int m_minimumDelay;
int m_maximumDelay;
 
QTimer''' m_minimumTimer;
QTimer* m_maximumTimer;
 
QString m_lastString;
int m_lastInt;
 
QString m_prefix;
QString m_postfix;
};
 
#endif // DELAYEDEXECUTIONTIMER_H
</code>
</code>


And here's the CPP code:
Finally, create a <tt>YourClass::onTextEdited</tt> slot that stores the newly edited filter text and starts the countdown to call the filtering method:
 
=== delayedexecutiontimer.cpp ===
 
<code>
<code>
/*
connect( m_textEdit, QLineEdit::textChanged, this, &YourClass::onTextEdited );
/*
Copyright © 2011, Andre Somers
All rights reserved.


File licence not repeated here for space reasons. See file "delayedexecutiontimer.h" for details of licence.
void YourClass::onTextEdited( const QString & newText )
*/
#include "delayedexecutiontimer.h"
#include <QTimer>
#include <QStringBuilder>
 
DelayedExecutionTimer::DelayedExecutionTimer(int maximumDelay, int minimumDelay, QObject''' parent):
QObject(parent),
m_minimumDelay(minimumDelay),
m_maximumDelay(maximumDelay),
m_minimumTimer(new QTimer(this)),
m_maximumTimer(new QTimer(this)),
m_lastInt(0)
{
{
connect(m_minimumTimer, SIGNAL (timeout()), SLOT (timeout()));
    m_filterText = newText;
connect(m_maximumTimer, SIGNAL (timeout()), SLOT (timeout()));
    m_typingTimer->start( 100 ); // This will fire filterEntries after 100 ms.
}
    // If the user types something before it fires, the timer restarts counting
 
DelayedExecutionTimer::DelayedExecutionTimer(QObject* parent):
QObject(parent),
m_minimumDelay(250),
m_maximumDelay(1000),
m_minimumTimer(new QTimer(this)),
m_maximumTimer(new QTimer(this)),
m_lastInt(0)
{
connect(m_minimumTimer, SIGNAL (timeout()), SLOT (timeout()));
connect(m_maximumTimer, SIGNAL (timeout()), SLOT (timeout()));
}
 
void DelayedExecutionTimer::timeout()
{
m_minimumTimer->stop();
m_maximumTimer->stop();
emit triggered();
emit triggered(m_prefix % m_lastString % m_postfix);
emit triggered(m_lastInt);
}
 
void DelayedExecutionTimer::trigger()
{
if (!m_maximumTimer->isActive()) {
m_maximumTimer->start(m_maximumDelay);
}
m_minimumTimer->stop();
m_minimumTimer->start(m_minimumDelay);
}
}
</code>


void DelayedExecutionTimer::trigger(QString string)
:''Note: the code above is adapted from a [http://stackoverflow.com/a/21945529/266309 StackOverflow answer] by [http://stackoverflow.com/users/2502409/nazar554 Nazar554].''
{
m_lastString = string;
trigger();
}
 
void DelayedExecutionTimer::trigger(int i)
{
m_lastInt = i;
trigger();
}
</code>

Latest revision as of 11:04, 25 July 2016

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Usecase

Have you ever created a text filter that can be used to filter a (big) list of items? If you did, you probably simply connected

QLineEdit::textChanged ( const QString & text )

to a method like

YourClass::filterEntries( const QString & filterText )

The problem is, now each character typed by the user triggers an update of the whole view, and the class has to go through all the items in your list over and over again. That could get expensive and slow, thereby instead of improving the user experience, you actually annoy the user.

There are many such cases where events can happen in quick succession, and you'd like your application to respond to these changes. On the one hand, it makes sense to respond to as many of those events in one go as possible, but on the other hand you don't want the update to take too much time after the user is done typing their filter string (or whatever it is you are waiting for).

Solution

The simplest solution to this problem is to use a QTimer. This allows you to, for instance, implement a text filter that waits for the user to stop typing and then run the query. Below is example code that shows how to implement this:

First, add a QTimer *m_typingTimer, and a QString m_filterText as private member variables for the class. Initialize the QTimer in the class constructor:

m_typingTimer = new QTimer( this );
m_typingTimer->setSingleShot( true ); // Ensure the timer will fire only once after it was started

Then, create a slot where the query will be performed, and connect the timer to it:

connect( m_typingTimer, &QTimer::timeout, this, &YourClass::filterEntries );

void YourClass::filterEntries()
{
    // The actual filtering code goes here, using the string stored in the m_filterText class variable
}

Finally, create a YourClass::onTextEdited slot that stores the newly edited filter text and starts the countdown to call the filtering method:

connect( m_textEdit, QLineEdit::textChanged, this, &YourClass::onTextEdited );

void YourClass::onTextEdited( const QString & newText )
{
    m_filterText = newText;
    m_typingTimer->start( 100 ); // This will fire filterEntries after 100 ms. 
    // If the user types something before it fires, the timer restarts counting
}
Note: the code above is adapted from a StackOverflow answer by Nazar554.