2015-05-09 86 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