简体   繁体   中英

PyQt4 How to get the “text” of a checkbox

So I'm trying to add the "text" associated with a checked checkbox to a list as soon as they're checked, and I'm doing this:

class Interface(QtGui.QMainWindow):

    def __init__(self):
        super(Interface, self).__init__()
        self.initUI()
        self.shops=[]

    def initUI(self):
        widthPx = 500
        heightPx = 500

        self.setGeometry(100,100,widthPx,heightPx)

        #menus
        fileMenu = menuBar.addMenu("&File")
        helpMenu = menuBar.addMenu("&Help")

        #labels
        shopList = _getShops()
        for i, shop in enumerate(shopList):
            cb = QtGui.QCheckBox(shop, self)
            cb.move(20, 15*(i)+50)
            cb.toggle()
            cb.stateChanged.connect(self.addShop)



        self.setWindowTitle("Absolute")
        self.show()

    def addShop(self, state):

        if state == QtCore.Qt.Checked:
            #I want to add the checkbox's text
            self.shops.append('IT WORKS')
        else:
            self.shops.remove('IT WORKS')

But instead of adding "IT WORKS" I want to add the text associated with the checkbox that was just selected.

I usually pass additionnal parameters in my signals/slots using partial Functools doc You can use it to pass your checkbox text.

First, import partial:

from functools import partial

Then, change your connect() method and pass your checkbox text:

cb.stateChanged.connect( partial( self.addShop, shop) )

To finish, update your addShop() method:

def addShop(self, shop, state):
    if state == Qt.Checked:
        self.shops.append(shop)
    else:
        try:
            self.shops.remove(shop)
        except:
            print ""

Notes:

  • I've added a try/except at the end because your checkboxes are checked by default. When you uncheck them, it tries to remove an unknow item from your self.shops list.

  • With this method, this is not the current checkbox text which is send to your method. It it the first text that was used to initialize your checkboxes. If, during the execution of your script, you modify the checkbox text, it will not be updated in your addShop method.

Update:

In fact, you can pass your checkbox in the partial:

cb.stateChanged.connect( partial( self.addShop, cb) )

and retrieve it this way:

def addShop(self, shop, state):
    if state == Qt.Checked:
        self.shops.append(shop.text())
    else:
        try:
            self.shops.remove(shop.text())
        except:
            print ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM