Alberto
Alberto

Reputation: 711

QT python connect passing arguments to function

Why this code works:

from PySide.QtCore import *
from PySide.QtGui import *
import sys
from functools import partial

import pyside # my code generated by QT Design

class MainDialog(QMainWindow, pyside.Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainDialog,self).__init__(parent)
        self.setupUi(self)


        self.connect(self.Connect_buttom, SIGNAL("clicked()"), partial(self.get_fb_token, "aaaaa","bbbbbb"))


    def get_fb_token(self,email,passwd): 
        print email
        print passwd


app = QApplication(sys.argv)
form = MainDialog()
form.show()
app.exec_()

And prints aaaaa and bbbbb

But if I change:

self.connect(self.Connect_buttom, SIGNAL("clicked()"), partial(self.get_fb_token, "aaaaa","bbbbbb"))

to

self.connect(self.Connect_buttom, SIGNAL("clicked()"), partial(self.get_fb_token, self.FB_username.text() ,self.FB_password.text()))

it does not print what I am introducing in the text boxes FB_password and FB_username (it does not crash but it does not print anything like if it is not sending both arguments to the function get_fb_token) ???

** Took the example from: http://www.blog.pythonlibrary.org/2013/04/10/pyside-connecting-multiple-widgets-to-the-same-slot/ Im using QT and pyside

Upvotes: 3

Views: 2551

Answers (1)

Bakuriu
Bakuriu

Reputation: 101909

The partial object is created when you define the connection, not when the event is triggered. Which means the FB_username.text() is called when connecting, so it will always print the contents that you have set in the designer.

To achieve what you want you have to use a function that retrieves those values when called. The simplest solution would be:

from PySide.QtCore import *
from PySide.QtGui import *
import sys

import pyside # my code generated by QT Design

class MainDialog(QMainWindow, pyside.Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainDialog,self).__init__(parent)
        self.setupUi(self)

        # use new-style signals & slots!
        self.Connect_buttom.clicked.connect(self.get_fb_token)

    def get_fb_token(self):
        email = self.FB_username.text()
        password = self.FB_password.text()

        print email
        print passwd


app = QApplication(sys.argv)
form = MainDialog()
form.show()
app.exec_()

If, for some reason, you don't want to modify get_fb_token, you can use a lambda like this:

self.Connect_buttom.clicked.connect(lambda: self.get_fb_token(self.FB_username.text(), self.FB_password.text()))

Upvotes: 2

Related Questions