Commit 1c1d7b86 authored by Ingo Klöcker's avatar Ingo Klöcker
Browse files

Select the text of an HTML label when it gets keyboard focus

This is a workaround for missing focus indicators for labels in many
Qt styles. To ensure that users see that a label has keyboard focus
we select its text.

GnuPG-bug-id: 5916
parent 45e703a5
......@@ -15,9 +15,12 @@
#include <QLabel>
#include <QObject>
#include <QTextDocument>
#include <algorithm>
#include "kleopatra_debug.h"
using namespace Kleo;
namespace
......@@ -56,6 +59,25 @@ QString Kleo::requiredText()
"required");
}
void Kleo::selectLabelText(QLabel *label)
{
if (!label || label->text().isEmpty()) {
return;
}
if (label->textFormat() == Qt::PlainText) {
label->setSelection(0, label->text().size());
} else if (label->textFormat() == Qt::RichText) {
// unfortunately, there is no selectAll(); therefore, we need
// to determine the "visual" length of the text by stripping
// the label's text of all formatting information
QTextDocument temp;
temp.setHtml(label->text());
label->setSelection(0, temp.toRawText().size());
} else {
qCDebug(KLEOPATRA_LOG) << "Label with unsupported text format" << label->textFormat() << "got focus";
}
}
LabelHelper::LabelHelper()
{
QAccessible::installActivationObserver(this);
......
......@@ -22,6 +22,12 @@ namespace Kleo
QString invalidEntryText();
QString requiredText();
/**
* Selects the text displayed by the label. Only \ref QLabel with text format
* \c Qt::PlainText or \c Qt::RichText are supported.
*/
void selectLabelText(QLabel *label);
/**
* Simple helper that sets the focus policy of the associated labels
* to \c Qt::StrongFocus if an assistive tool is active.
......
......@@ -11,6 +11,7 @@
#include <config-kleopatra.h>
#include "htmllabel.h"
#include "utils/accessibility.h"
#include <QAccessible>
......@@ -74,6 +75,21 @@ void HtmlLabel::setLinkColor(const QColor &color)
d->updateText();
}
void HtmlLabel::focusInEvent(QFocusEvent *ev)
{
QLabel::focusInEvent(ev);
// if the text label gets focus, then select its text; this is a workaround
// for missing focus indicators for labels in many Qt styles
const Qt::FocusReason reason = ev->reason();
const auto isKeyboardFocusEvent = reason == Qt::TabFocusReason
|| reason == Qt::BacktabFocusReason
|| reason == Qt::ShortcutFocusReason;
if (!text().isEmpty() && isKeyboardFocusEvent) {
Kleo::selectLabelText(this);
}
}
bool HtmlLabel::focusNextPrevChild(bool next)
{
const bool result = QLabel::focusNextPrevChild(next);
......
......@@ -30,6 +30,7 @@ public:
void setLinkColor(const QColor &color);
protected:
void focusInEvent(QFocusEvent *ev) override;
bool focusNextPrevChild(bool next) override;
private:
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment