-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighlightDelegate.cpp
More file actions
73 lines (55 loc) · 2.29 KB
/
HighlightDelegate.cpp
File metadata and controls
73 lines (55 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// HighlightDelegate.cpp
#include "HighlightDelegate.h"
#include <QPainter>
#include <QTextLayout>
HighlightDelegate::HighlightDelegate(QObject* parent)
: QStyledItemDelegate(parent) {
}
void HighlightDelegate::setPattern(const QString& pattern) {
m_pattern = pattern;
}
void HighlightDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
const QModelIndex& index) const {
painter->save();
// 1. Draw the base item using the default style (preserves selection background)
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
QStyledItemDelegate::paint(painter, opt, index);
// 2. Check if we need to highlight any search pattern
QString text = index.data(Qt::DisplayRole).toString();
if (m_pattern.isEmpty())
{
painter->restore();
return; // No search pattern: no custom highlighting
}
QString lowerText = text.toLower();
QString lowerPattern = m_pattern.toLower();
int matchStart = lowerText.indexOf(lowerPattern);
if (matchStart < 0) {
painter->restore();
return; // No match: nothing to highlight
}
// 3. Perform manual drawing over the text to highlight the match
QRect textRect = option.rect;
painter->setClipRect(textRect);
QFontMetrics fm(option.font);
QString before = text.left(matchStart);
QString match = text.mid(matchStart, m_pattern.length());
QString after = text.mid(matchStart + m_pattern.length());
int x = textRect.left() + 4; // Small left margin
int y = textRect.top() + (textRect.height() + fm.ascent() - fm.descent()) / 2;
// Measure width of each part
int beforeWidth = fm.horizontalAdvance(before);
int matchWidth = fm.horizontalAdvance(match);
// Highlight background for matched text
QRect matchRect(x + beforeWidth, textRect.top(), matchWidth, textRect.height());
painter->fillRect(matchRect, QColor(255, 120, 120)); // light red
// Set text pen color depending on selection state
QColor penColor = option.state & QStyle::State_Selected
? option.palette.highlightedText().color()
: option.palette.text().color();
painter->setPen(penColor);
// Draw the whole text
painter->drawText(x, y, before + match + after);
painter->restore();
}