[英]PyQt4 Qtreewidget - get hierarchy text if child checkbox is checked
[英]PyQt4 How to get the “text” of a checkbox
因此,我尝试将与选中的复选框相关联的“文本”添加到列表中,然后立即将它们添加到列表中,我正在这样做:
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”,而是要添加与刚选中的复选框关联的文本。
我通常使用partial
Functools文档在信号/插槽中传递附加参数。您可以使用它传递复选框文本。
首先,导入部分:
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方法中对其进行更新。
更新:
实际上,您可以在部分框中传递您的复选框:
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 ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.