【问题标题】:PyQt4 How to get the "text" of a checkboxPyQt4如何获取复选框的“文本”
【发布时间】:2015-01-28 23:08:03
【问题描述】:

所以我试图在选中复选框后立即将与选中复选框关联的“文本”添加到列表中,我正在这样做:

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')

但我不想添加“IT WORKS”,而是想添加与刚刚选中的复选框相关联的文本。

【问题讨论】:

标签: python pyqt


【解决方案1】:

我通常使用partial 在我的信号/插槽中传递附加参数 Functools doc 您可以使用它来传递您的复选框文本。

首先,导入部分:

from functools import partial

然后,更改您的 connect() 方法并传递您的复选框文本:

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

要完成,请更新您的 addShop() 方法:

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

注意事项:

  • 我在末尾添加了一个 try/except,因为您的复选框默认处于选中状态。当您取消选中它们时,它会尝试从您的 self.shops 列表中删除一个未知项目。

  • 使用此方法,这不是发送到您的方法的当前复选框文本。它是用于初始化复选框的第一个文本。如果在执行脚本期间修改了复选框文本,则不会在 addShop 方法中更新它。

更新:

其实你可以在partial中传递你的checkbox:

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

并以这种方式检索它:

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

【讨论】:

    猜你喜欢
    • 2014-04-20
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多