单击项目

时间:2015-09-09 09:43:11

标签: python pyqt signals

我有一个包含多行的表,在第0列我给它添加了一个复选框,定义如下:

for char in accounts:
    for columnNumber in range(numberColumns):
        pWidget = QWidget()
        pCheckbox = QCheckBox()
        pLayout = QVBoxLayout(pWidget)
        pLayout.addWidget(pCheckbox)
        pLayout.setAlignment(Qt.AlignCenter)
        pLayout.setContentsMargins(0, 0 ,0, 0)
        pCheckbox.setCheckState(False)
        pCheckbox.clicked.connect(self.handleItemClicked)
        pWidget.setLayout(pLayout)
        self.mainAccountTable.insertRow(currentRowCount)
        self.mainAccountTable.setCellWidget(currentRowCount, 0, pWidget)
        self.mainAccountTable.setItem(currentRowCount, 1, QTableWidgetItem(char[1]))

我有一个连接方法来处理点击:

def handleItemClicked(self):
    try:
        #self.accountsSelected = []
        for account in range(self.mainAccountTable.rowCount()):
            if self.mainAccountTable.cellWidget(account, 0).findChild(type(QCheckBox())).isChecked():
                self.accountsSelected.add(self.mainAccountTable.item(account, 1).text())
                print ("yes:",self.accountsSelected)
            else:
                self.accountsSelected.remove(self.mainAccountTable.item(account, 1).text())
                print ("no:",self.accountsSelected)
    except Exception as e:
        print ("Error",e)

困扰我的是,这是完美的,但只有当我选中或取消选中第一个复选框(第0行,第0列)时才能刷新结果。我也尝试将信号与toggled相连......相同的结果。 那么,当我检查或取消选中除第一行以外的其他行时,如何更新结果呢?提前谢谢。

后来编辑: 我更新它的代码,输出是这样的: 如果我检查除第一个以外的其他复选框,这是输出: 'Account1' 如果我选择了,让我们说5个帐户,我也选择了第一个复选框,这是输出:

    yes: {'Account2', 'Account1'}
    yes: {'Account2', 'Account1'}
    yes: {'Account2', 'Account1', 'Account3'}
    yes: {'Account2', 'Account1', 'Account3', 'Account4'}
    yes: {'Account2', 'Account1', 'Account3', 'Account4', 'Account5'}
    Error: 'Account 6' #is not selected which is true, BUT WHY is checking also for that?!?!

1 个答案:

答案 0 :(得分:0)

有n = rowCount()个pCheckBox。但是只有clicked() - 1个pCheckBox的信号连接到self.handleItemClicked()。取代码的第一部分中的connect(),连接每个pCheckBox。由于有n个pCheckbox,pWidgets,pLayouts删除了'self':

            pWidget = QWidget()
            pCheckbox = QCheckBox()
            pLayout = QVBoxLayout(pWidget)
            pLayout.addWidget(pCheckbox)
            pLayout.setAlignment(Qt.AlignCenter)
            pLayout.setContentsMargins(0, 0 ,0, 0)
            pCheckbox.setCheckState(False)
            pCheckBox.clicked.connect(self.handleItemClicked)
            pWidget.setLayout(pLayout)
            self.mainAccountTable.insertRow(currentRowCount)
            self.mainAccountTable.setCellWidget(currentRowCount, 0, pWidget)