Skip to content Skip to sidebar Skip to footer

Change Text Color When Hovered Over A Link In Pyqt

I am trying to change the colour of the text when hovered over a link in QLabel. I couldn't achieve it using the label provided by PyQt, So I am trying to create a custom label by

Solution 1:

It doesn't work properly because the label is centered, while your call to boundingRect() obviously isn't:

Returns the rectangle that is covered by ink if character ch were to be drawn at the origin of the coordinate system.

Moreover, you're using a bigger font, and fontMetrics couldn't know anything about that, since it's based on the widget's font().

The solution is to use the correct boundingRect() implementation with a constructed font metrics based on the font you're going to use:

defcheckHover(self, pos=None):
        if pos isNone:
            pos = self.mapFromGlobal(QtGui.QCursor.pos())
        font = self.font()
        font.setPixelSize(14)
        fm = QtGui.QFontMetrics(font)
        textRect = fm.boundingRect(self.rect(), self.alignment(), "StackOverflow")
        self.setText('''
            <a href="{link}" style="color: {color}; font: 14px; text-decoration: None;">
            {alias}</a>'''.format(
                link='https://stackoverflow.com', 
                alias='StackOverflow', 
                color='blue'if pos in textRect else'black', 
            ))

    defenterEvent(self, event):
        self.checkHover()
        super(LinkLabel, self).enterEvent(event)

    defmouseMoveEvent(self, event):
        self.checkHover(event.pos())
        super(LinkLabel, self).mouseMoveEvent(event)

    defleaveEvent(self, event):
        self.checkHover()
        super(LinkLabel, self).leaveEvent(event)

Note that I used setPixelSize() because you set the font size in pixels, while you should better use points instead, as they would be device independent (which is the preferred practice for font rendering).

Post a Comment for "Change Text Color When Hovered Over A Link In Pyqt"