gpt4 book ai didi

python - PyQt5:检查动态创建的复选框是否存在并引用它们

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

代码的基本布局

在这里,每次用户单击PushButton 'Press me'时,都会生成一个新的复选框。

from PyQt5 import QtWidgets, QtGui, QtCore

count = 1

class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)

self.vlayout = QtWidgets.QVBoxLayout()
self.pushButton1 = QtWidgets.QPushButton("Press me", self)
self.pushButton1.clicked.connect(self.addCheckbox(count))
self.pushButton2 = QtWidgets.QPushButton("OK", self)
self.vlayout.addWidget(self.pushButton1)
self.vlayout.addWidget(self.pushButton2)

self.setLayout(self.vlayout)

def addCheckbox(self,count):
global count
self.vlayout.addWidget(str(count),QtWidgets.QCheckBox())
count = count +1

application = QtWidgets.QApplication(sys.argv)
window = Window()
window.setWindowTitle('Hello')
window.resize(250, 180)
window.show()
sys.exit(application.exec_())

我想做什么?

现在您将拥有独特的复选框,每个复选框都有不同的编号,我想添加更多功能。

每次用户选择特定复选框时,我想知道用户在单击 PushButton OK 后单击了哪个复选框。例如:我单击复选框 1 -> 确定 -> 在屏幕上打印 1

我该怎么做?

PS:我们需要考虑用户从未点击Press me的可能性,因此不会生成复选框并直接点击OK

最佳答案

只需使用一个列表来存储QCheckBox,并通过迭代进行验证。

from PyQt5 import QtWidgets, QtGui, QtCore


class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)

self.vlayout = QtWidgets.QVBoxLayout(self)
self.pushButton1 = QtWidgets.QPushButton("Press me")
self.pushButton1.clicked.connect(self.addCheckbox)
self.pushButton2 = QtWidgets.QPushButton("OK")
self.pushButton2.clicked.connect(self.onClicked)

self.vlayout.addWidget(self.pushButton1)
self.vlayout.addWidget(self.pushButton2)

self.checkboxes = []

def addCheckbox(self):
checkbox = QtWidgets.QCheckBox()
self.checkboxes.append(checkbox)
self.vlayout.addWidget(checkbox)

def onClicked(self):
for i, checkbox in enumerate(self.checkboxes):
if checkbox.isChecked():
print("print {} on the screen".format(i))

if __name__ == '__main__':
import sys

application = QtWidgets.QApplication(sys.argv)
window = Window()
window.setWindowTitle('Hello')
window.resize(250, 180)
window.show()
sys.exit(application.exec_())

关于python - PyQt5:检查动态创建的复选框是否存在并引用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51405824/

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