Issue
I have created a QTableWidget having four columns. The first column is a text field and the remaining three are radio buttons. Objective is to make all radio buttons in a row exclusive.
The code snippet is as below:
#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
For some reason, the radio buttons in a row are not exclusive. We could check upto four radio buttons and they are distributed through out the table.
Solution
What is happening is that the variables created within a loop are often destroyed when the loop is terminated by the garbage collector, one way to avoid this is to pass a parent to 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_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.