Reputation: 17
New to pyQt, I'm trying to fill a Qcombobox with a list of items, and then, to retrieve the text selected by the user. Everything works fine except that, when CurrentIndexChanged signal is triggered, I can't get the index of the selection, but not the text, with .currentText() in my method, because I have an error telling me that I can't call my widget in the method. Python does not recognize my QCombobox in the method, so that I can't use .currentText(), and I can't figure why.
Thanks !
See my code below.
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("Votre territoire")
layout = QVBoxLayout()
listCom = self.getComINSEE()
cbCommunes = QComboBox()
cbCommunes.addItems(listCom)
cbCommunes.currentIndexChanged.connect(self.selectionChange)
layout.addWidget(cbCommunes)
cbCommunes = QWidget()
cbCommunes.setLayout(layout)
self.setCentralWidget(cbCommunes)
def getComINSEE(self):
# some code to fill my list com
return com
def selectionChange(self, i):
# Error : unhandled AttributeError "'MainWindow' object has no attribute 'cbCommunes'"
texte = self.cbCommunes.currentText()
print(f"Index {i} pour la commune {i}")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Upvotes: 1
Views: 2159
Reputation: 13641
To get access to an object in any class method, you need to make this object an attribute of the class.
change cbCommunes
toself.cbCommunes
- everywhere.
from PyQt5.Qt import *
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("Votre territoire")
listCom = self.getComINSEE()
self.cbCommunes = QComboBox()
self.cbCommunes.addItems(listCom)
self.cbCommunes.currentIndexChanged.connect(self.selectionChange)
centralwidget = QWidget()
self.setCentralWidget(centralwidget)
layout = QVBoxLayout(centralwidget)
layout.addWidget(self.cbCommunes)
def getComINSEE(self):
# some code to fill my list com
com = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5',]
return com
def selectionChange(self, i):
# Error : unhandled AttributeError "'MainWindow' object has no attribute 'cbCommunes'"
texte = self.cbCommunes.currentText()
print(f"Index {i} pour la commune {i}, texte -> {texte}")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Upvotes: 1