Reputation: 1632
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
Upvotes: 1
Views: 248
Reputation: 120578
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
:
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()
Upvotes: 3
Reputation: 4038
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.
Upvotes: 1