1 | // Copyright (C) 2017 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
3 | |
4 | #include "qquickmnemoniclabel_p.h" |
5 | |
6 | #include <QtQuick/private/qquicktext_p_p.h> |
7 | |
8 | QT_BEGIN_NAMESPACE |
9 | |
10 | QQuickMnemonicLabel::QQuickMnemonicLabel(QQuickItem *parent) |
11 | : QQuickText(parent) |
12 | { |
13 | } |
14 | |
15 | QString QQuickMnemonicLabel::text() const |
16 | { |
17 | return m_fullText; |
18 | } |
19 | |
20 | void QQuickMnemonicLabel::setText(const QString &text) |
21 | { |
22 | if (m_fullText == text) |
23 | return; |
24 | |
25 | m_fullText = text; |
26 | updateMnemonic(); |
27 | } |
28 | |
29 | bool QQuickMnemonicLabel::isMnemonicVisible() const |
30 | { |
31 | return m_mnemonicVisible; |
32 | } |
33 | |
34 | void QQuickMnemonicLabel::setMnemonicVisible(bool visible) |
35 | { |
36 | if (m_mnemonicVisible == visible) |
37 | return; |
38 | |
39 | m_mnemonicVisible = visible; |
40 | updateMnemonic(); |
41 | |
42 | if (isComponentComplete()) |
43 | forceLayout(); |
44 | } |
45 | |
46 | static QTextLayout::FormatRange underlineRange(int start, int length = 1) |
47 | { |
48 | QTextLayout::FormatRange range; |
49 | range.start = start; |
50 | range.length = length; |
51 | range.format.setFontUnderline(true); |
52 | return range; |
53 | } |
54 | |
55 | // based on QPlatformTheme::removeMnemonics() |
56 | void QQuickMnemonicLabel::updateMnemonic() |
57 | { |
58 | QString text(m_fullText.size(), QChar::Null); |
59 | int idx = 0; |
60 | int pos = 0; |
61 | int len = m_fullText.size(); |
62 | QList<QTextLayout::FormatRange> formats; |
63 | while (len) { |
64 | if (m_fullText.at(i: pos) == QLatin1Char('&') && (len == 1 || m_fullText.at(i: pos + 1) != QLatin1Char('&'))) { |
65 | if (m_mnemonicVisible && (pos == 0 || m_fullText.at(i: pos - 1) != QLatin1Char('&'))) |
66 | formats += underlineRange(start: pos); |
67 | ++pos; |
68 | --len; |
69 | if (len == 0) |
70 | break; |
71 | } else if (m_fullText.at(i: pos) == QLatin1Char('(') && len >= 4 && |
72 | m_fullText.at(i: pos + 1) == QLatin1Char('&') && |
73 | m_fullText.at(i: pos + 2) != QLatin1Char('&') && |
74 | m_fullText.at(i: pos + 3) == QLatin1Char(')')) { |
75 | // a mnemonic with format "\s*(&X)" |
76 | if (m_mnemonicVisible) { |
77 | formats += underlineRange(start: pos + 1); |
78 | } else { |
79 | int n = 0; |
80 | while (idx > n && text.at(i: idx - n - 1).isSpace()) |
81 | ++n; |
82 | idx -= n; |
83 | pos += 4; |
84 | len -= 4; |
85 | continue; |
86 | } |
87 | } |
88 | text[idx] = m_fullText.at(i: pos); |
89 | ++pos; |
90 | ++idx; |
91 | --len; |
92 | } |
93 | text.truncate(pos: idx); |
94 | |
95 | QQuickTextPrivate::get(t: this)->layout.setFormats(formats); |
96 | QQuickText::setText(text); |
97 | } |
98 | |
99 | QT_END_NAMESPACE |
100 | |
101 | #include "moc_qquickmnemoniclabel_p.cpp" |
102 |