1

I try to google it but no answer, look like QListWidget isnt dynamic module

Here is my code:

        listwidget = QtWidgets.QListWidget()
        for a in range (0,3):
            listwidget.addItem(str(a))

        button_layout = QHBoxLayout()
        self.buttfind = QPushButton('Find')
        self.buttfind.clicked.connect(self.find)
        self.buttmerge = QPushButton('Merge')
        self.buttmerge.clicked.connect(self.merge)
        button_layout.addWidget(self.buttfind)
        button_layout.addWidget(self.buttmerge)

        main_layout.addWidget(listwidget)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)

    def merge(self):
        print('a')
        listwidget.addItem(str('asd'))


I get the problem at:

    def merge(self):
        print('a')
        listwidget.addItem(str('asd'))

The error: listwidget.addItem(str('asd')) NameError: name 'listwidget' is not defined

ForteD
  • 41
  • 4

1 Answers1

0

listwidget only has function scope, so that variable reference is lost at the end of your first function.

Changing listwidget to self.listwidget will give the variable instance scope.

101
  • 8,514
  • 6
  • 43
  • 69