There is something like this:

import sys from PyQt4.QtWebKit import QWebView from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl html = u''' <ul class="nav"> <li><a href="index.pyw">Главная</a></li> <li><a href="link/index.php">Ссылка 1</a></li> <li><a href="link/index2.php">Ссылка 2</a></li> </ul><br />''' app = QApplication(sys.argv) browser = QWebView() browser.setHtml(html) browser.show() app.exec_() 

Is it possible to somehow run the python code when clicking on a link?

    1 answer 1

    Implement a handler class that contains your python slot in the slot that you want to run when the link is activated.

    Connect this slot with the void QWebView::linkClicked(const QUrl& url) .

    In order for this signal to be sent, you must set the QWebView property of the linkDelegationPolicy your QWebView to DelegateAllLinks .

    All together in the code:

     import sys from PyQt4.QtWebKit import QWebView, QWebPage from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl, QObject, pyqtSlot, SIGNAL, SLOT class Handler(QObject): def __init__(self, parent = None): QObject.__init__(self, parent) @pyqtSlot("QUrl") def slotActivateLink(self, url): print("Debug: " + url.toString() + " activated") # Здесь на ваш код замените html = u''' <ul class="nav"> <li><a href="index.pyw">Главная</a></li> <li><a href="link/index.php">Ссылка 1</a></li> <li><a href="link/index2.php">Ссылка 2</a></li> </ul><br />''' app = QApplication(sys.argv) browser = QWebView() browser.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) handler = Handler() QObject.connect(browser, SIGNAL("linkClicked(const QUrl&)"), handler, SLOT("slotActivateLink(const QUrl&)")) browser.setHtml(html) browser.show() app.exec_() 
    • Thanks a lot! Great code. Just can not figure out how to code: browser = QWebView() browser.setHtml(html) browser.show() run inside the slotActivateLink slot? - MyNick
    • What exactly do you want to do in the slot? What result is needed? - aleks.andr
    • When you click on the link opened a new window created using browser.setHtml (html) - MyNick
    • Then in the slot code you need to create this window: def slotActivateLink(self, url): subrowser = QWebView(self) subrowser.setHtml(html) subrowser.show() - aleks.andr
    • def slotActivateLink(self, url): bro = QWebView() bro.setHtml(u'''<a href="index.pyw">Главная 2</a>''') bro.show() - When clicked, nothing not happening - MyNick