PyQt,设置特定数量的行编辑输入

问题描述 投票:0回答:1

我想一步设置输入的数量(输入=行编辑),单击按钮后,我要获得行编辑的数量。 (如图所示。)

enter image description here

例如,我有3个输入参数,因此我想将数字设置为3,单击按钮并获得3个输入字段(行编辑)。

我不想为每个选项创建新的小部件并替换旧的小部件。 (我有4个参数的输入值可变,组合太多。)最终,我可以在行编辑中将多个值插入一个值,但是这些选项对我来说听起来都不是很好。你有什么建议吗?

谢谢您的回答。

python pyqt qlineedit
1个回答
0
投票

尝试:

from PyQt5 import QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.resize(300,300)
        self.items = []
        self.item_count = 0

        label = QtWidgets.QLabel("NUMBER OF LINE EDITS")

        self.spinBox = QtWidgets.QSpinBox(self)
        self.spinBox.setRange(0, 7)
        self.spinBox.valueChanged.connect(self.set_item_count)

        button = QtWidgets.QPushButton("apply", clicked=self.on_clicked)

        self.lineEdit = QtWidgets.QLineEdit

        groupBox = QtWidgets.QGroupBox("Line Edit")
        self.item_layout = QtWidgets.QVBoxLayout(groupBox)
        self.item_layout.addStretch(2)

        g_layout = QtWidgets.QGridLayout(self)
        g_layout.addWidget(label, 0, 0, 1, 2)
        g_layout.addWidget(self.spinBox, 0, 2, 1, 1)
        g_layout.addWidget(button, 1, 0, 1, 1)
        g_layout.addWidget(groupBox, 2, 0, 5, 3)

    def on_clicked(self):
        print( *[ item.text() for item in  self.items[:self.spinBox.value()] ], sep="\n" )

    def set_item_count(self, new_count:int):
        n_items = len(self.items)
        for ii in range(n_items, new_count):
            item = self.lineEdit(self)
            self.items.append(item)
            self.item_layout.insertWidget(n_items, item)
        for ii in range(self.item_count, new_count):
            self.item_layout.itemAt(ii).widget().show()
        for ii in range(new_count, self.item_count):
            self.item_layout.itemAt(ii).widget().hide()
        self.item_count = new_count

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    window = Widget()
    window.show()
    app.exec()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.