gpt4 book ai didi

python - 如何在 for 循环中创建多个复选框?

转载 作者:行者123 更新时间:2023-12-01 01:14:38 25 4
gpt4 key购买 nike

我刚刚开始使用 PyQt5 开发一个新的 python 项目。程序必须根据需要创建尽可能多的复选框。我正在尝试使用 for 循环。但我无法使用复选框名称,因为每次我使用 for 循环创建一个新复选框时,它都会被覆盖。我的问题: 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())

最佳答案

您可以使用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_())

enter image description here

关于python - 如何在 for 循环中创建多个复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com