我想一步设置输入数量(输入=行编辑),单击按钮后我想获取行编辑数量。 (如图所示。)
例如,我有 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()
关于python - PyQt,设置特定数量的行编辑输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566306/