Kirigami-addons

commandbarfiltermodel.cpp
1// SPDX-FileCopyrightText: 2021 Waqar Ahmed <waqar.17a@gmail.com>
2// SPDX-FileCopyrightText: 2022 Carl Schwan <carl@carlschwan.eu>
3// SPDX-License-Identifier: LGPL-2.0-or-later
4
5#include "commandbarfiltermodel_p.h"
6#include "actionsmodel_p.h"
7#include <KFuzzyMatcher>
8#include <QAction>
9
10CommandBarFilterModel::CommandBarFilterModel(QObject *parent)
11 : QSortFilterProxyModel(parent)
12{
13}
14
15QString CommandBarFilterModel::filterString() const
16{
17 return m_pattern;
18}
19
20void CommandBarFilterModel::setFilterString(const QString &string)
21{
22 if (m_pattern == string) {
23 return;
24 }
25 // MUST reset the model here, we want to repopulate
26 // invalidateFilter() will not work here
27 beginResetModel();
28 m_pattern = string;
29 endResetModel();
30 Q_EMIT filterStringChanged();
31}
32
33bool CommandBarFilterModel::lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
34{
35 const int l = sourceLeft.data(KCommandBarModel::Score).toInt();
36 const int r = sourceRight.data(KCommandBarModel::Score).toInt();
37 return l < r;
38}
39
40bool CommandBarFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
41{
42 if (m_pattern.isEmpty()) {
43 return true;
44 }
45
46 const QModelIndex idx = sourceModel()->index(sourceRow, 0, sourceParent);
47 if (!(qvariant_cast<QAction *>(idx.data(Qt::UserRole))->isEnabled())) {
48 return false;
49 }
50
51 const QString actionName = idx.data(Qt::DisplayRole).toString();
52 KFuzzyMatcher::Result res = KFuzzyMatcher::match(m_pattern, actionName);
53 sourceModel()->setData(idx, res.score, KCommandBarModel::Score);
54 return res.matched;
55}
56
57#include "moc_commandbarfiltermodel_p.cpp"
KCOREADDONS_EXPORT Result match(QStringView pattern, QStringView str)
QVariant data(int role) const const
UserRole
int toInt(bool *ok) const const
QString toString() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Dec 20 2024 11:49:32 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.