Reputation: 304
I am trying to feed an unspecified number of comboboxes to a user. Once the user selects inputs for the combo boxes I want to be able to print out those combobox inputs after the submit button is clicked. Currently I can only print the last one because my comboboxes are being overwritten. I thought to do a cb.format(i) and call each respectively but I was unable to get it to work.
import sys
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.resize(200, 200)
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.lay = QHBoxLayout(self.centralwidget)
self.MakeButtons(5)
def MakeButtons(self, x):
for i in range(x):
self.cb = QComboBox(self)
self.cb.addItem("ID")
self.cb.addItem("Num")
self.cb.addItem("Bi")
self.cb.addItem("Cat")
self.lay.addWidget(self.cb)
self.btn = QPushButton('Submit', self)
self.btn.clicked.connect(self.printingaction)
def printingaction(self):
#print('Current item: {0}'.format( self.cb.currentIndex() )) # ComboBox's index
print('Current index: {0}'.format( self.cb.currentText() )) # ComboBox's text
app = QApplication([])
window = Window()
window.show()
app.exec()
Upvotes: 2
Views: 37
Reputation: 17291
You can collect the combo boxes into a list and then iterate the list when the submit button is pressed.
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.resize(200, 200)
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.lay = QHBoxLayout(self.centralwidget)
self.boxes = [] # list of combo boxes
self.MakeButtons(5)
def MakeButtons(self, x):
for _ in range(x):
cb = QComboBox(self)
cb.addItem("ID")
cb.addItem("Num")
cb.addItem("Bi")
cb.addItem("Cat")
self.boxes.append(cb)
self.lay.addWidget(cb)
self.btn = QPushButton('Submit', self)
self.btn.clicked.connect(self.printingaction)
def printingaction(self):
for box in self.boxes: # iterate list of combo boxes.
print('Current index: {0}'.format(box.currentText()))
Upvotes: 2