PySide中QTableWidget行内单选按钮互斥失效问题求助
解决QTableWidget每行单选按钮互斥的问题
我帮你排查了下代码里的问题,核心原因是你在循环中创建的QButtonGroup是局部变量,当循环迭代到下一行时,上一行的按钮组会被Python的垃圾回收机制销毁,导致它无法持续管理该行单选按钮的互斥性。另外代码里还有个小拼写错误:buttonC.setCheched(True)应该是setChecked(少了字母k),这会导致C类的按钮无法被正确选中。
下面是修正后的方案:
关键修复点
- 用一个列表保存所有行的
QButtonGroup,确保它们的生命周期和表格一致,不会被提前销毁 - 修正拼写错误
setCheched为setChecked
修正后的完整代码
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QRadioButton, QButtonGroup # 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"]) # 创建列表保存所有行的按钮组,避免被垃圾回收 button_groups = [] 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: # 修正拼写错误:setCheched -> setChecked buttonC.setChecked(True) # Add radio button to corresponding table item searchView.setCellWidget(index, 1, buttonA) searchView.setCellWidget(index, 2, buttonB) searchView.setCellWidget(index, 3, buttonC) # 创建按钮组并添加当前行的三个按钮 buttonGroup = QButtonGroup() buttonGroup.addButton(searchView.cellWidget(index, 1)) buttonGroup.addButton(searchView.cellWidget(index, 2)) buttonGroup.addButton(searchView.cellWidget(index, 3)) # 将按钮组加入列表保存 button_groups.append(buttonGroup) index += 1
这样修改后,每行的三个单选按钮就会保持互斥状态,同一时间只能选中该行的一个按钮,不同行的按钮之间不会互相影响。
内容的提问来源于stack exchange,提问作者goku
相关产品推荐
相关产品推荐

