Q-bart
Q-bart

Reputation: 1591

How can I make link on web page in window using pyqt4?

I have a problem. Can I make a link on the web page in the window and when the user clicks on it, the web page will be open in the browser. For example:

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)
main = QtGui.QWidget()
main.setGeometry(200, 200, 200, 100)
label = QtGui.QLabel('<a href="http://stackoverflow.com/">Stackoverflow/</a>')
box = QtGui.QVBoxLayout()
box.addWidget(label)
main.setLayout(box)

main.show()
sys.exit(app.exec_())

Is it really?

Upvotes: 8

Views: 9329

Answers (2)

Jablonski
Jablonski

Reputation: 18504

It is of course good that you found answer, but there is special class, which allows you to open URL in default browser or files in default editors/players etc. It is QDesktopServices. For example:

from PyQt5.QtGui import QDesktopServices
from PyQt5.QtCore import QUrl

class MainWindow(QMainWindow, Ui_MainWindow):
    def link(self, linkStr):

        QDesktopServices.openUrl(QUrl(linkStr))

    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.label.linkActivated.connect(self.link)
        self.label.setText('<a href="http://stackoverflow.com/">Stackoverflow/</a>')

This example is definitely larger, but you should know about QDesktopServices, because it is very useful class.

Upvotes: 11

Q-bart
Q-bart

Reputation: 1591

Sorry. I have already searched the answer.

label.setText('<a href="http://stackoverflow.com/">Link</a>')
label.setOpenExternalLinks(True)

Upvotes: 11

Related Questions