Gianluca Gianluca - 9 months ago 63
Python Question

PyQt: How to load a url from a menu item

I have a main window with some buttons and a plot. I added a file menu, using Qt Designer. Now, if I run my app, everything is good and I can see a typical menu bar. The problem is, I want to click on the menu bar and perform an action - I want to open an internet web page with the default browser. Can someone help me?

This is the code generated with pyuic4 from Qt Designer (I show just the code for the file menu):

self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1445, 21))
self.menuFile = QtGui.QMenu(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.actionFsa_format = QtGui.QAction(MainWindow)

As you can see I have a file menu, and a tool-button with an actionFsa_format action. I want to click this and open an external url.

Answer Source

You need to connect the triggered signal of your action to a handler.

So in the __init__ of your main window, do this:


And your openUrl method could be something like this:

    def openUrl(self):
        url = QtCore.QUrl('')
        if not QtGui.QDesktopServices.openUrl(url):
            QtGui.QMessageBox.warning(self, 'Open Url', 'Could not open url')