The easiest way would be to create a list for the widgets, and populate it with each row of widgets added as a tuple.
Note that I slightly changed the for
cycle to make it more readable, and I also moved the setRowCount()
and setColumnCount()
outside it, as continuously setting them in the cycle with the same values is useless.
I also changed the widget references, which are now local variables and not instance attribute anymore: when using loops it doesn't make a lot of sense to overwrite an instance attribute for every cycle, as it will always be lost on the next iteration.
class my_app(QMainWindow):
def __init__(self):
super(my_app, self).__init__()
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.list_products()
self.ui.pushButton.clicked.connect(self.current_index)
self.widgetList = []
def list_products(self):
self.widgetList.clear()
curs.execute("SELECT productName,productId FROM products_list")
products=curs.fetchall()
curs.execute("SELECT shipmentTime FROM shipmentTime ORDER BY id")
shipmentTime=curs.fetchall()
self.ui.productlist.setRowCount(len(products))
self.ui.productlist.setColumnCount(3)
for row, i in enumerate(products):
label = QtWidgets.QLabel(i[0])
combo = QtWidgets.QComboBox()
combo.addItems(j[0] for j in shipmentTime)
checkbox = QtWidgets.QCheckBox(i[1])
checkbox.setObjectName(i[1])
self.ui.productlist.setCellWidget(row, 0, checkbox)
self.ui.productlist.setCellWidget(row, 1, label)
self.ui.productlist.setCellWidget(row, 2, combo)
self.widgetList.append((checkbox, label, combo))
def current_index(self):
for checkbox, label, combo in self.widgetList:
if checkbox.isChecked():
print(checkbox.objectName(), label.text(), combo.currentText())
Do note that the above is the most basic (and probably more pythonic) possibility; you can do the same without the list and using the functions provided by QTableWidget, which is more "Qt-onic" ;-) :
def current_index(self):
for row in range(self.ui.productlist.rowCount()):
checkbox = self.ui.productlist.cellWidget(row, 0)
if isinstance(QtWidgets.QCheckBox) and checkbox.isChecked():
label = self.ui.productlist.cellWidget(row, 1)
combo = self.ui.productlist.cellWidget(row, 2)
print(checkbox.objectName(), label.text(), combo.currentText())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…