1

The main window is declared in Class1. I am trying to create an object of Class2, create a widget( a push button) and connect it to a slot.

import sys
from PyQt4 import QtGui,QtCore

class Class2(object):
    def __init__(self,parent):
        return
    def button(self,parent):
        self.print_button=QtGui.QPushButton("print hello",parent)
        self.print_button.show()
        self.print_button.clicked.connect(self.print_hello)

    def print_hello(self,parent):
        print 'hello'



class Class1(QtGui.QMainWindow):
    def __init__(self):
        super(Class1, self).__init__()
        self.welcomeScreen()

    def welcomeScreen(self):
        obj=Class2(self)
        obj.button(self)


def main():
    app = QtGui.QApplication(sys.argv)
    mw = Class1()
    mw.show()
    sys.exit(app.exec_())


if __name__=='__main__':
    main()

Now, the button is getting created but the slot is not working. How to deal with this problem?

sudeepdino008
  • 3,194
  • 5
  • 39
  • 73

1 Answers1

0

Your print_hello takes 2 arguments, and you pass it only a one.

Try this:

self.print_button.clicked.connect(lambda: self.print_hello(self))
Rafał Łużyński
  • 7,083
  • 5
  • 26
  • 38
  • i don't understand the lambda?? why its not running without the lambda? – fecub Feb 08 '13 at 14:57
  • 1
    because you have to pass pointer to function, which lambda returns. Without lambda `self.print_hello(self)` would return `None`, and hence `None` would be passed as function pointer, so slot would not work. Lambda is a really great tool. It creates new 'anonymoys' function that does what we define and returns pointer to it. In this example it runs `self.print_hello(self)`. Without lambda we can't pass arguments to pointer. – Rafał Łużyński Feb 08 '13 at 15:00
  • 1
    Actually, the OP is using the new style signals, checkout the [New-style Signal and Slot Support](http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html), please update your post to reflect this –  Feb 08 '13 at 17:39
  • Well this is od,d because I read somewhere that this is a new style and I was using it this way all the time :O Anyway thanks for pointing this out. – Rafał Łużyński Feb 08 '13 at 18:26