Issue
I've written this simple script(for concept understanding) to better understand how to handle/manage dynamically created combo boxes.
So in this example, we have a total of 5 dynamically created combo boxes, each containing a list of 3 variables.
When selecting any variable the function comboFunction
is run.
What I want to understand, is:
- How can I retrieve the index of the combo box being selected
- The index of the variable being selected.
And print in the comboFunction
the index of the Combobox and the variable.
For example in the screenshot below, I selected the combo box at index 0 and the variable at index 0.
import sys
from PySide6 import QtWidgets
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QGridLayout(self)
self.lists = ["1","2","3"]
for i in range(5):
self.combobox = QtWidgets.QComboBox(self)
self.combobox.addItems(self.lists)
self.layout.addWidget(self.combobox, i,0)
self.combobox.currentIndexChanged.connect(self.comboFunction)
def comboFunction(self):
print("hello world")
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec())
Solution
A simple way would be to add its number as an attribute and read it later:
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QGridLayout(self)
self.lists = ["1", "2", "3"]
for i in range(5):
self.combobox = QtWidgets.QComboBox(self)
self.combobox.id_number = i
self.combobox.addItems(self.lists)
self.layout.addWidget(self.combobox, i, 0)
self.combobox.currentIndexChanged.connect(self.comboFunction)
def comboFunction(self, idx):
combo = self.sender()
print(f"Selected the variable {idx} from combo {combo.id_number}")
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())
Answered By - noEmbryo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.