views:

64

answers:

1

Hi, I`m starting with PyQt4 and right now I have a problem with events.

I have one main class let say MainWindow. MainWindow has a list of buttons of type ButtonX (inherence form QPushButton). I would like to achieve one of 2 solutions (depends which is easier).

1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)

2) Second solution is to run a method defined in ButtonX class.

What I tried is:

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0).buttonMethod())

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue()"))

and even this line occure suspend Python interpreter

QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue"))
+2  A: 

1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)

You can access the source of an event using QObject.sender(). But, as the instructions indicate, it's often better to use QSignalMapper or do things in a more object oriented fashion.

2) Second solution is to run a method defined in ButtonX class.

Look carefully at what you typed for the last argument of the first connect call:

self.getButton(0, 0).buttonMethod()

The above will evaluate getButton with parameters 0, 0 and then, on that object, call the buttonMethod method. So, unless buttonMethod returns a method, you are using the return value of buttonMethod as the last parameter to the connect call. If this method returns a function, then this is just fine.

Rather, I would expect to see something like the following:

self.getButton(0, 0).buttonMethod # note no parenthesis at end

Take a look at the PyQt examples directory provided with PyQt as they'll demonstrate the exact syntax and serve as good examples.

Here's one small example:

class MW(QMainWindow):
    def __init__(self, *args)
        QMainWindow.__init__(self, *args)
        layout = QHBoxLayout(self)
        self.b1 = QPushButton("Button1")
        self.b2 = QPushButton("Button2")
        layout.addWidget(self.b1)
        layout.addWidget(self.b2)
        self.connect(self.b1, SIGNAL("clicked()"), self.buttonWasPressed)
        self.connect(self.b2, SIGNAL("clicked()"), self.buttonWasPressed)

    def buttonWasPressed(self):
        print "button %s was pressed" % self.sender()
Kaleb Pederson