【问题标题】:PyQt5: Check the existance of dynamically created Checkboxes and Refer themPyQt5:检查动态创建的复选框的存在并引用它们
【发布时间】:2018-12-26 14:21:50
【问题描述】:

代码的基本布局

这里,每次用户点击PushButton 'Press me',都会生成一个新的CheckBox。

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 -> OK -> print 1 on the screen

我该怎么做?

PS:我们需要考虑用户从不点击Press me的可能性,所以不会生成任何复选框,直接点击OK

【问题讨论】:

标签: python python-3.x pyqt pyqt5


【解决方案1】:

只需使用一个列表来存储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_())  

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2013-03-09
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2017-08-01
    相关资源
    最近更新 更多