2015-05-09 88 views
1

我有一个名为“selectAllCheckBox”的复选框。当处于选中状态时,列表视图中所有复选框(动态创建)都应该更改为checked状态,并且当“selectAllCheckBox”复选框处于Unchecked状态时,所有动态创建的复选框应该更改为未选中状态。PyQt和Python中的复选框问题

self.dlg.selectAllCheckBox.stateChanged.connect(self.selectAll) 
def selectAll(self): 
    """Select All layers loaded inside the listView""" 

    model = self.dlg.DatacheckerListView1.model() 
    for index in range(model.rowCount()): 
     item = model.item(index) 
     if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked: 
      item.setCheckState(QtCore.Qt.Checked) 

什么上面的代码确实它使列表视图中的动态复选框选中状态,即使“SelectAllCheckBox”是未选中状态。请帮助我如何使用python解决此问题。有没有什么可以做到的信号,如当复选框被选中或未选中连接到插槽而不是stateChanged?

回答

2

stateChanged信号发送checked state,因此狭槽可以被重新写为:

def selectAll(self, state=QtCore.Qt.Checked): 
    """Select All layers loaded inside the listView""" 

    model = self.dlg.selectAllCheckBox.model() 
    for index in range(model.rowCount()): 
     item = model.item(index) 
     if item.isCheckable(): 
      item.setCheckState(state) 

(NB:如果在列表视图中的所有行具有复选框,则isCheckable线可以被省略)

+0

代码完美地工作。但是我和你们之间的区别在于你已经通过了国家作为方法中的争论。那么你可以说清楚吗?你的代码现在在做什么? – harinish

+0

@harinish。我给'state'参数一个默认值,这样'selectAll'可以不带任何参数被调用。当'selectAll'连接到一个发送状态的信号时,默认参数将被覆盖。 – ekhumoro

+0

我的问题是“stateChanged()”信号的默认状态是什么。当selectAllCheckBox被选中并且被用户取消选中时,stateChanged也会被调用。因此,如果selectAll被选中,它将调用方法“selectAll”并将状态更改为“Checked”。但是当selectAll复选框未选中时,它如何取消选中所有动态复选框?我们没有在我们的方法中设置任何状态,如“未检查”? stateChanged()信号也可以在不传递任何参数的情况下工作。但是在http://doc.qt.io/qt-4.8/qcheckbox.html#stateChanged中,它被要求传递一个参数 – harinish