如何获取动态生成的QSpinBox控件的所有值?
Fix: Get Values from All Generated QSpinBoxes
Hey Ivan, I see the problem here—let's sort this out! The issue is that in your loop, you're reassigning self.quantity_pp every time you create a new QSpinBox. By the end of the loop, this variable only holds a reference to the last spin box you made, which is why you can only get its value when clicking the button.
Here's how to fix it:
Instead of overwriting a single variable, store all your QSpinBox instances in a list. This way you'll have a reference to every spin box you create.
Modified Code:
class CreateSpuWindow(QMainWindow): def __init__(self, value): super().__init__() uic.loadUi('ui/statement_spu_1.ui', self) self.value = value # QSpinBox的数量 # 1. Initialize an empty list to store all QSpinBoxes self.spin_boxes = [] for i in range(value): self.spu_label = QLabel(self) self.spu_label.setText(f"SPU №{i+1}. PP:") self.quantity_pp = QSpinBox(self) self.quantity_pp.setValue(1) self.quantity_pp.setMinimum(1) self.gridLayout_2.addWidget(self.spu_label, 2 * i, 0) self.gridLayout_2.addWidget(self.quantity_pp, 2 * i, 1) # 2. Add each new spin box to the list self.spin_boxes.append(self.quantity_pp) self.next_tu_spu_2Button.clicked.connect(self.next_wind_spu_btn) self.back_btn.clicked.connect(self.back_btn_cl) def next_wind_spu_btn(self): data = [] # 3. Iterate over the list to get every spin box's value for spin_box in self.spin_boxes: data.append(spin_box.value()) print(data) quantity_spu = self.value self.ReadyTableSpuWindow = ReadyTableSpuWindow(quantity_spu) self.ReadyTableSpuWindow.show() self.close() def back_btn_cl(self): self.close() self.QuantitySpuWindow = QuantitySpuWindow() self.QuantitySpuWindow.show()
What changed?
- Added
self.spin_boxes = []to initialize a container for all spin boxes. - After creating each
self.quantity_pp, we add it toself.spin_boxesso we don't lose the reference. - In
next_wind_spu_btn, we loop throughself.spin_boxesinstead of trying to use the singleself.quantity_ppvariable, which now collects values from every spin box you generated.
This way, when you click the button, you'll get a list of values from all your QSpinBoxes, not just the last one.
内容的提问来源于stack exchange,提问作者Ivan W
相关产品推荐
相关产品推荐

