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

标签 python pyqt qlineedit

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

enter image description here

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

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

感谢您的回答。

最佳答案

尝试一下:

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

关于python - PyQt,设置特定数量的行编辑输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566306/

相关文章:

python - 编码练习 : Timbits-Fix the bugs and pass all of the tests

python - 使用 QWebView 请求的 POST 请求

python - 如何在另一个函数中使用 QDateEdit 小部件中设置的用户值?

macos - 如何在 QLineEdit 中放置静态文本(后缀、前缀)?

python - 从多列(其中一列)的开头自动完成

python - 关于使用默认参数值的 python 名称的问题

python - python 中的 numba CUDA 非常慢

python - 如何创建 Pandas 数据框的字典,并将数据框返回到 excel 工作表中?

python - 从pyqt5的主页打印

python - 将行编辑传递给上下文管理器以设置验证器