Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underline QLabel's text "on hover"

Tags:

c++

qt

qlabel

I want to turn the text green and underline it when the mouse cursor goes over a QLabel, however, it just turns green, it does not get underlined.

  QLabel:hover { color: green; text-decoration: underline;}

What am I doing wrong?

EDIT: Fixed, I used:

void QClickableLabel::enterEvent (QEvent *event)
{
    Q_UNUSED (event);
    setStyleSheet ("QLabel { color: green; text-decoration: underline; }");
}

void QClickableLabel::leaveEvent (QEvent *event)
{
    Q_UNUSED (event);
    setStyleSheet ("QLabel { color: black; }");
}
like image 780
Mattia F. Avatar asked Aug 31 '25 20:08

Mattia F.


2 Answers

According to Qt documentation (for both Qt 4 and Qt 5), QLabel "Does not support the :hover pseudo-state". Guess it's plain luck that it even changes the color...

To emulate, you could create a QLabel subclass and promote your widget to it. Then implement enterEvent() and leaveEvent() methods, doing necessary changes to the widget, e.g.

void MyLabel::enterEvent(QEvent* event)
{
    QFont f = font();
    f.setUnderline(true);
    setFont(f);
}

void MyLabel::leaveEvent(QEvent* event)
{
    QFont f = font();
    f.setUnderline(false);
    setFont(f);
}
like image 142
mike.dld Avatar answered Sep 04 '25 03:09

mike.dld


You can use the following construction:

QLabel *text= new QLabel("Your text"); text->setStyleSheet("font-weight: bold; color: green; text-decoration: underline");

I'm using this and it's works wonderfully. ;)

like image 38
Campos33 Avatar answered Sep 04 '25 04:09

Campos33