0

I have an application which should open a web browser address after button click. Main function look like this:

class MainWindow(QtGui.QDialog):
    def __init__( self, parent = None ):
        super( MainWindow, self ).__init__( parent = parent )
        self.button_layout = QtGui.QHBoxLayout(self)
        self.webButton = PicButton(QtGui.QPixmap("images/button.png"))
        self.filmButton.clicked.connect(openWebpage("http://some.web.adress"))
        self.button_layout.addWidget(self.webButton)

And function for opening a web browser looks this way:

def openWebpage(address):
    try:
        import webbrowser

        webbrowser.open(address)

    except ImportError as exc:
        sys.stderr.write("Error: failed to import settings module ({})".format(exc))

After running this code, no application window visible, web browser fires immediately, and console returns:

Failed to connect signal clicked().

Simple functions connected to this button works properly (for instance - printing text to console). Any ideas?

Mateusz Wójt
  • 109
  • 2
  • 15
  • Is `self.filmButton.clicked.connect(openWebpage("http://some.web.adress"))` correct? I mean exactly the `openWebpage("http://some.web.adress")`-part. I've thought it is only permitted to use it as `self.filmButton.clicked.connect(openWebpage)`. Also, provide a type of "filmButton". – VP. Dec 11 '14 at 13:13
  • [Check this](http://stackoverflow.com/questions/13894866/pyside-connection-error-runtimeerror-failed-to-connect-signal-clicked#comment19156148_13894993), @VictorPolevoy is right. – Anshul Goyal Dec 11 '14 at 13:16

2 Answers2

0

To pass an argument in the slot you need to construct a lambda expression:

self.filmButton.clicked.connect(lambda: openWebpage("http://some.web.adress"))

To explain this a little more, the connect() method accepts a callable object as its argument. The lambda expression, which is basically an anonymous function, is one such callable object. You could also wrap your function call in the functools module's partial() method to achieve the same thing. For more about what constitutes a Python callable, see What is a "callable" in Python?

Community
  • 1
  • 1
nb1987
  • 1,400
  • 1
  • 11
  • 12
0

As people said a bit earlier - use lambda, or use a normal slot which gives (to me at least) more readability.

def __init__(self):
    self.filmButton.clicked.connect(self._film_button_clicked)

@pyqtSlot() # note that this is not really necessary
def _film_button_clicked(self):
    self.openWebpage('http://some.web.adress')
VP.
  • 15,509
  • 17
  • 91
  • 161