使用pyside的qtablewidget中的单选按钮

时间:2018-05-29 05:03:54

标签: python pyside

我创建了一个有四列的QTableWidget。第一列是文本字段,其余三个是单选按钮。目标是将所有单选按钮排成一行。

代码段如下:

#Create a table having one row and four columns
searchView = QTableWidget(1,4)
#Input data to create table
dirNames = {'A':['/tmp', '/tmp/dir1'], 'B':['/tmp/dir2'], 'C':['/tmp/dir3']}
#calculate the number of rows needed in table
rowCount = len(dirNames["A"]) + len(dirNames["B"]) + len(dirNames["C"])
searchView.setRowCount(rowCount)
#Set the horizontal header names
searchView.setHorizontalHeaderLabels(["DIR", "A", "B", "C"])
index = 0 
for action in dirNames:
    for paths in dirNames[action]:
        #Create QTableWidgetItem for directory name
        item = QTableWidgetItem(paths)
        searchView.setItem(index, 0, item)
        #Create three radio buttons
        buttonA = QRadioButton()
        buttonB = QRadioButton()
        buttonC = QRadioButton()
        #Check the radio button based on action
        if action == 'A':
            buttonA.setChecked(True)
        elif action == 'B':
            buttonB.setChecked(True)
        else:
            buttonC.setCheched(True)
        #Add radio button to corresponding table item
        searchView.setCellWidget(index, 1, buttonA)
        searchView.setCellWidget(index, 2, buttonB)
        searchView.setCellWidget(index, 3, buttonC)
        #Since setCellWidget transfers the ownership of all radio buttons to qtablewidget Now all radio buttons in table are exclusive
        #So create a buttongroup and add all radio buttons in a row to it so that only radio buttons in a row are exclusive
        buttonGroup = QButtonGroup()
        buttonGroup.addButton(searchView.cellWidget(index, 1)) 
        buttonGroup.addButton(searchView.cellWidget(index, 2)) 
        buttonGroup.addButton(searchView.cellWidget(index, 3)) 
        index += 1

由于某种原因,连续的单选按钮不是独占的。我们可以检查最多四个单选按钮,它们会在表格中分发。

1 个答案:

答案 0 :(得分:0)

正在发生的事情是,当循环被垃圾收集器终止时,循环中创建的变量经常被销毁,避免这种情况的一种方法是将父级传递给QButtonGroup

import sys

from PySide.QtGui import QApplication, QTableWidget, QTableWidgetItem, \
    QButtonGroup, QRadioButton

app = QApplication(sys.argv)

searchView = QTableWidget(0, 4)
colsNames = ['A', 'B', 'C']
searchView.setHorizontalHeaderLabels(['DIR'] + colsNames)
dirNames = {'A': ['/tmp', '/tmp/dir1'], 'B': ['/tmp/dir2'],
            'C': ['/tmp/dir3']}

rowCount = sum(len(v) for (name, v) in dirNames.items())
searchView.setRowCount(rowCount)

index = 0

for letter, paths in dirNames.items():
    for path in paths:
        it = QTableWidgetItem(path)
        searchView.setItem(index, 0, it)
        group = QButtonGroup(searchView)
        for i, name in enumerate(colsNames):
            button = QRadioButton()
            group.addButton(button)
            searchView.setCellWidget(index, i + 1, button)
            if name == letter:
                button.setChecked(True)
        index += 1

searchView.show()
sys.exit(app.exec_())