无法在方法中使用我的小部件Qcombobox,为什么?

2024-06-25 22:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

Tags: 方法文本selfcominitdefargskwargs
1条回答
网友
1楼 · 发布于 2024-06-25 22:50:53

要访问任何类方法中的对象,需要将该对象设为类的属性

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_())

enter image description here

相关问题 更多 >