pyQt的新手,我试图用项目列表填充Qcombobox,然后检索用户选择的文本。一切正常,除了在触发CurrentIndexChanged信号时,在我的方法中使用.currentText()无法获取选择的索引,但无法获取文本,因为我有一个错误告诉我无法调用我的方法中的小部件。Python无法在该方法中识别我的QCombobox,因此无法使用.currentText(),也无法确定原因。
谢谢 !
请参阅下面的代码。
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()
要使用任何类方法访问对象,您需要使该对象成为类的属性。
更改cbCommunes
为self.cbCommunes
-无处不在。
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_())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句