我刚刚开始使用PyQt5开发一个新的python项目。该程序有必要使复选框尽可能多。我正在尝试使用for循环。但是我无法使用checkboxname,因为每次我用for循环创建一个新的checkboxname时,它都会被覆盖。我的问题:for循环完成后,如何查看选择了哪个?
from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import *
from functies import dataOphalen
import os
import json
data = {}
checkLijst = []
alleVrucht = []
def radioAanmaken():
col = 0
for i in data:
rij = 0
lbl = QLabel(i)
ui.gridcheck.addWidget(lbl,rij,col)
rij+=1
for b in data[i]:
check = QCheckBox(b)
ui.gridcheck.addWidget(check,rij,col)
#save name in variable
checkLijst.append({"naam":check,"col":col,"rij":rij,"vrucht":i})
rij+=1
check = QCheckBox(("Alle "+i))
ui.gridcheck.addWidget(check,rij,col)
alleVrucht.append({"naam":check,"vrucht":i})
col+=1
app = QtWidgets.QApplication([])
ui = uic.loadUi("addNew.ui")
data = dataOphalen("percelen.json")
radioAanmaken()
ui.show()
app.exec()
编辑解决方案:
for i in range(ui.gridcheck.count()):
checkb = ui.gridcheck.itemAt(i).widget()
if checkb.isChecked():
print(checkb.text())
答案 0 :(得分:1)
您可以使用isChecked()
来查询是否选中了一个复选框。
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Window(QWidget):
def __init__(self, many):
super().__init__()
self.layoutH = QHBoxLayout()
for i in range(many):
self.checkbox = QCheckBox("chBox-{}".format(i+1))
self.checkbox.setCheckState(Qt.Unchecked)
self.layoutH.addWidget(self.checkbox)
self.layoutH.setAlignment(Qt.AlignCenter)
self.label = QLabel("selected QCheckBox: ")
self.button = QPushButton("Query whether or not a checkbox is checked")
self.button.clicked.connect(self.ButtonClicked)
layoutV = QVBoxLayout(self)
layoutV.addLayout(self.layoutH)
layoutV.addWidget(self.label)
layoutV.addWidget(self.button)
def ButtonClicked(self):
checked_list = []
for i in range(self.layoutH.count()):
chBox = self.layoutH.itemAt(i).widget()
if chBox.isChecked():
checked_list.append(chBox.text())
self.label.setText("selected QCheckBox: " + str(list(checked_list)))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window(7)
window.resize(350, 300)
window.show()
sys.exit(app.exec_())