0

I want to create a window with four buttons, and print the corresponding content when click button. Here is my code,

# -*- encoding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

class ExampleApp(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        center = QtGui.QWidget()
        self.setCentralWidget(center)
        layout = QtGui.QVBoxLayout()
        center.setLayout(layout)
        data = ['1', '2', '3', '4']
        btns = {}
        for x in data:
            btns[x] = QtGui.QPushButton(x)
            layout.addWidget(btns[x])
        for x in data:
            QtCore.QObject.connect(btns[x], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx(x))
        # QtCore.QObject.connect(btns['1'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('1'))
        # QtCore.QObject.connect(btns['2'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('2'))
        # QtCore.QObject.connect(btns['3'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('3'))
        # QtCore.QObject.connect(btns['4'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('4'))

    @staticmethod
    def printx(x):
        print x


app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()

When bind the events manually, it works well, click the 1,2,3,4 button, and the screan prints 1,2,3,4

QtCore.QObject.connect(btns['1'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('1'))
QtCore.QObject.connect(btns['2'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('2'))
QtCore.QObject.connect(btns['3'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('3'))
QtCore.QObject.connect(btns['4'], QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx('4'))

However, when I bind the events in a for loop, the errors occur. Clicking 1,2,3,4 button results in printing 4,4,4,4

for x in data:
            QtCore.QObject.connect(btns[x],QtCore.SIGNAL(_fromUtf8("clicked()")), lambda: self.printx(x))

Please explain the reason for me, and give the solution for connecting SINGAL and SLOT in loop, thanks a lot!

Ryan
  • 345
  • 3
  • 11

0 Answers0