-1

I want to take variable board from def buttonClicked5(self) to def closeEvent(self, event): what should I do?

class MainWindow(QtWidgets.QMainWindow):         

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def buttonClicked5(self):  
        board = Arduino(self.ui.comboBox.currentText())
        communication_start = "Communication Successfully started"
        self.ui.lineEdit_4.setText(communication_start)

    def closeEvent(self, event):
        board.exit()        
            
CHL
  • 57
  • 7
  • 4
    I strongly recommend you to find some tutorial and the proper documentation about classes, instances, attributes and OOP in general, and take your time to seriously and patiently study all that, because if you want to use PyQt you cannot ignore such basical and elementary aspects. – musicamante Jan 13 '22 at 06:08
  • [same question has been asked here](https://stackoverflow.com/questions/10139866/calling-variable-defined-inside-one-function-from-another-function) – Azhar Uddin Sheikh Jan 13 '22 at 06:11

1 Answers1

3

You can set it as self.board. Like this:

class MainWindow(QtWidgets.QMainWindow):         

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def buttonClicked5(self):  
        self.board = Arduino(self.ui.comboBox.currentText())
        communication_start = "Communication Successfully started"
        self.ui.lineEdit_4.setText(communication_start)

    def closeEvent(self, event):
        self.board.exit()      
Leonardo Lima
  • 373
  • 2
  • 10
  • pop up error `AttributeError: 'MainWindow' object has no attribute 'board'` – CHL Jan 13 '22 at 06:04
  • 1
    Since you're declaring the board on `buttonClicked5()` method, you must call it before you call `closeEvent()`, otherwise the `self.board` attribute will not be declared. An alternative, you can declare the `self.board` on your constructor method and give it a default value so you code can see it before the `buttonClicked5()` is called, but you probably will have some bugs calling a `None` variable. – Leonardo Lima Jan 13 '22 at 06:11
  • @ChenAndy Use `if hasattr(self, 'board'):` `self.board.exit()` – musicamante Jan 13 '22 at 11:57