Commit 2ac361b4 authored by Ingo Klöcker's avatar Ingo Klöcker
Browse files

Allow setting the color of the rendered link

Qt does not use the QPalette::Link color when rendering rich text.
Therefore, we do it directly via the style-attribute of the <a> tag.

GnuPG-bug-id: 5535
parent 3464ec14
......@@ -13,28 +13,69 @@
#include "urllabel.h"
#include <QAccessible>
#include <QPalette>
using namespace Kleo;
UrlLabel::UrlLabel(QWidget *parent)
: QLabel{parent}
class UrlLabel::Private
{
setTextFormat(Qt::RichText);
setTextInteractionFlags(Qt::TextBrowserInteraction);
}
UrlLabel *q;
public:
Private(UrlLabel *q) : q{q} {}
void UrlLabel::setUrl(const QUrl &url, const QString &text)
void ensureLinkColorIsValid();
void updateLabel();
QUrl url;
QString text;
QColor linkColor;
};
void UrlLabel::Private::ensureLinkColorIsValid()
{
if (!linkColor.isValid()) {
linkColor = q->palette().link().color();
}
}
void UrlLabel::Private::updateLabel()
{
// we prepend a zero-width-space character to work around a bug in QLabel::focusNextPrevChild(false)
// which makes it impossible to leave the label with Shift+Tab if the text starts with a link
static const QString templateString{QLatin1String{"&#8203;<a href=\"%1\">%2</a>"}};
static const QString templateString{QLatin1String{"&#8203;<a style=\"color: %1;\" href=\"%2\">%3</a>"}};
if (url.isEmpty()) {
clear();
q->clear();
return;
}
setText(templateString.arg(url.url(QUrl::FullyEncoded), text.isEmpty() ? url.toDisplayString().toHtmlEscaped() : text.toHtmlEscaped()));
ensureLinkColorIsValid();
q->setText(templateString.arg(
linkColor.name(),
url.url(QUrl::FullyEncoded),
text.isEmpty() ? url.toDisplayString().toHtmlEscaped() : text.toHtmlEscaped()));
}
UrlLabel::UrlLabel(QWidget *parent)
: QLabel{parent}
, d{new Private{this}}
{
setTextFormat(Qt::RichText);
setTextInteractionFlags(Qt::TextBrowserInteraction);
}
Kleo::UrlLabel::~UrlLabel() = default;
void UrlLabel::setUrl(const QUrl &url, const QString &text)
{
d->url = url;
d->text = text;
d->updateLabel();
}
void UrlLabel::setLinkColor(const QColor &color)
{
d->linkColor = color;
d->updateLabel();
}
void UrlLabel::focusInEvent(QFocusEvent *event)
......
......@@ -12,6 +12,8 @@
#include <QLabel>
#include <memory>
namespace Kleo
{
......@@ -20,15 +22,22 @@ class UrlLabel : public QLabel
Q_OBJECT
public:
explicit UrlLabel(QWidget *parent = nullptr);
~UrlLabel() override;
void setUrl(const QUrl &url, const QString &text = {});
void setLinkColor(const QColor &color);
protected:
void focusInEvent(QFocusEvent *event) override;
bool focusNextPrevChild(bool next) override;
private:
using QLabel::setText;
private:
class Private;
std::unique_ptr<Private> d;
};
}
Markdown is supported
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