1

I have a QTextBrowser() object:

self.PAddressLink = QTextBrowser()

I need to click on a link placed on this QTextBrowser, and it should open a new dialog box.

self.PAddressLink.setHtml("<html><body><a href=#>+Add Permanent Address</a></body></html>")

I can open the new window with the below code anyhow:

self.PAddressLink.anchorClicked.connect(self.AddPAddress) #self.AddPAddress is the method of displaying a dialog box.

But I need to know if I can place the self.AddPAddress in the href and avoid using the below extra statement:

self.PAddressLink.anchorClicked.connect(self.AddPAddress) #self.AddPAddress 
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Ejaz
  • 1,504
  • 3
  • 25
  • 51

2 Answers2

3

Assuming all the methods are defined on the same object (e.g. self), you could set the method names in the href attribute:

self.PAddressLink.setHtml('<a href="AddPAddress">...</a>')
self.PAddressLink.anchorClicked.connect(self.handleLink)

and then use getattr to call the method:

def handleLink(self, url):
    if url.scheme():
        # handle normal urls here if necessary...
    else:
        getattr(self, url.toString())()

Here's a complete demo using both QLabel and QTextBrowser:

screenshot

from PyQt5 import QtCore, QtGui, QtWidgets

html = """
<p><a href="https://www.google.com">Url Link</a></p>
<p><a href="myMethod">Method Link</a></p>
"""

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.label = QtWidgets.QLabel(html)
        self.browser = QtWidgets.QTextBrowser()
        self.browser.setOpenLinks(False)
        self.browser.setHtml(html)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.browser)
        layout.addWidget(self.label)
        self.label.linkActivated.connect(self.handleLink)
        self.browser.anchorClicked.connect(self.handleLink)

    def handleLink(self, url):
        url = QtCore.QUrl(url)
        if url.scheme():
            # handle real urls
            QtGui.QDesktopServices.openUrl(url)
        else:
            # handle methods
            getattr(self, url.toString())()

    def myMethod(self):
        QtWidgets.QMessageBox.information(self, 'Test', 'Hello World!')

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    app.exec()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
1

Most likely not. Atleast not any easy way. You'd be just reimplementing the signals and slots system most likely.

Just as with buttons, you have to connect the click signal to a slot. That's how it is designed to work.

Sevanteri
  • 3,749
  • 1
  • 23
  • 27
  • what if I need to use multiple links in a single QTextBrowser, I will have to use multiple QTextBrowsers then? – Ejaz Jan 26 '15 at 08:28
  • The anchorClicked signal passes the url to the slot, so you could make `self.AddPAddress` handle the urls differently. – Sevanteri Jan 26 '15 at 08:34