如何实现菜单栏刷新按钮以重置所有下拉框至初始状态?
The problem with your current fill_box1 method is that calling setupUi(self) completely reinitializes your UI. While this does reset the combo boxes, it also wipes out all the signal connections you set up earlier (like self.submit_pb.clicked.connect(self.fill_box)), which is why your other functionality breaks after clicking refresh.
Instead of reloading the entire UI, you can directly reset each combo box to its initial state without losing existing connections. Here's how to do it properly:
Step 1: Save Initial Combo Box State (Optional but Recommended)
If you ever plan to dynamically modify the items in your combo boxes, save their initial items when the app starts. Add this to your __init__ method:
def __init__(self): super(MyQtApp,self).__init__() self.setupUi(self) self.showNormal() # Save initial items for each combo box (in case you modify them later) self.initial_model_items = [self.model_cb.itemText(i) for i in range(self.model_cb.count())] self.initial_size_items = [self.size_cb.itemText(i) for i in range(self.size_cb.count())] self.initial_color_items = [self.color_cb.itemText(i) for i in range(self.color_cb.count())] # Set up your signal connections self.submit_pb.clicked.connect(self.fill_box) self.Menu()
Step 2: Update the Refresh Method
Replace your fill_box1 method with this code to reset the combo boxes properly:
def fill_box1(self): # Reset each combo box to its initial empty selection (index 0) self.model_cb.setCurrentIndex(0) self.size_cb.setCurrentIndex(0) self.color_cb.setCurrentIndex(0) # Uncomment these lines if you need to restore the original items (e.g., if you added/removed items dynamically) # self.model_cb.clear() # self.model_cb.addItems(self.initial_model_items) # self.size_cb.clear() # self.size_cb.addItems(self.initial_size_items) # self.color_cb.clear() # self.color_cb.addItems(self.initial_color_items)
Quick Fix for a Typo in Your Code
I noticed a small mistake in your fill_box method: you're getting the model text twice instead of the color text. Fix this line:
# Wrong: color = self.model_cb.currentText() color = self.color_cb.currentText()
This approach keeps all your existing signal connections intact while resetting the combo boxes to their initial state. The refresh button will now work as expected without breaking other functionality.
内容的提问来源于stack exchange,提问作者Junaid Khalid

