File indexing completed on 2024-12-01 04:36:51

0001 /*
0002    SPDX-FileCopyrightText: 2021-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "searchwithdelaylineedit.h"
0008 #include <KLocalizedString>
0009 #include <QTimer>
0010 
0011 SearchWithDelayLineEdit::SearchWithDelayLineEdit(QWidget *parent)
0012     : QLineEdit(parent)
0013     , mSearchTimer(new QTimer(this))
0014 {
0015     setClearButtonEnabled(true);
0016     setPlaceholderText(i18n("Search Word..."));
0017     connect(mSearchTimer, &QTimer::timeout, this, &SearchWithDelayLineEdit::slotSearchTimerFired);
0018     connect(this, &SearchWithDelayLineEdit::textChanged, this, &SearchWithDelayLineEdit::slotSearchTextEdited);
0019     connect(this, &SearchWithDelayLineEdit::returnPressed, this, &SearchWithDelayLineEdit::slotSearchTimerFired);
0020 }
0021 
0022 SearchWithDelayLineEdit::~SearchWithDelayLineEdit() = default;
0023 
0024 void SearchWithDelayLineEdit::setDelayMs(std::chrono::milliseconds value)
0025 {
0026     mMilliseconds = value;
0027 }
0028 
0029 void SearchWithDelayLineEdit::slotSearchTimerFired()
0030 {
0031     mSearchTimer->stop();
0032     if (!text().trimmed().isEmpty()) {
0033         Q_EMIT searchRequested(text());
0034     } else {
0035         Q_EMIT searchCleared();
0036     }
0037 }
0038 
0039 void SearchWithDelayLineEdit::slotSearchTextEdited()
0040 {
0041     if (mSearchTimer->isActive()) {
0042         mSearchTimer->stop(); // eventually
0043     }
0044 
0045     mSearchTimer->setSingleShot(true);
0046     mSearchTimer->start(mMilliseconds);
0047 }
0048 
0049 #include "moc_searchwithdelaylineedit.cpp"