Volodymyr
Volodymyr

Reputation: 1442

pyqt: add clicked event for a Qlabel

I've created label: self.labelOnlineHelp = QLabel('<a href="http://example.com">Online Help</a>') and want to make it clickable. Ideally it should open firefox (but not a default browser) and also change mouse to pointer (in a nutshell: just to create an usual hyperlink). I see that there is no clicked event in qlabel. Is there any way how to perform this in a simple way?

Upvotes: 5

Views: 7288

Answers (2)

okorkut
okorkut

Reputation: 521

You need to reimplement QLabel class and override the mousePressEvent or mouseReleaseEvent. Here is a simple example:

class MyLabel(QLabel):
    def __init__(self, parent):
        QLabel.__init__(self, parent)
        self.link = "http://www.example.com"

    def mousePressEvent(self, event):
        # open the link on your browser
        webbrowser.get('firefox').open_new_tab(self.link)

Upvotes: 3

Brendan Abel
Brendan Abel

Reputation: 37599

You can do this using setOpenExternalLinks

self.labelOnlineHellp.setOpenExternalLinks(True)

If you want to do something different than the default behavior (ie. open link in the default browser), you can connect to the linkActivated signal instead (don't use setOpenExternalLinks to True if you're handling the opening of the link yourself).

self.labelOnlineHelp.linkActivated.connect(self.link_handler)

def link_handler(self, link):
    subprocess.call(['/path/to/firefox', link])

Upvotes: 5

Related Questions