Problems with Open-Source Downloads read https://www.qt.io/blog/problem-with-open-source-downloads and https://forum.qt.io/post/638946

Set QLineEdit text from function in second file



  • Hello, iam trying to set text from function in other file and it is not working can you help me with this ? Let me give you example....

    My button is connected to function clicked0 and this button should change text.
    This is my main file

       class Window(QMainWindow):
    
       def __init__(self):
           super().__init__()
           self.textboxvalue2 = ""
    
    
           self.setWindowTitle("Samuel calcâ„¢")
           self.setGeometry(200, 200, 259, 258)
    
           self.textbox = QLineEdit(self)
           self.textbox.move(5, 5)
           self.textbox.resize(188, 35)
           self.textbox.setText(str(self.textboxvalue2))
           self.textbox.setPlaceholderText("Enter numbers")
           self.textboxValue = self.textbox.text()
    
           self.b10 = QtWidgets.QPushButton(self)
           self.b10.setText("0")
           self.b10.move(68, 219)
           self.b10.resize(60, 35)
           self.b10.clicked.connect(self.clicked0)
    
    
           self.show()
    
       def setExpression(self,expression):
           print(expression)
           self.textbox.setText(str(expression))
    
    
       def clicked0(self):
           import AbstratctNumberButton
           AbstratctNumberButton.onClick()
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = Window()
        sys.exit(app.exec())
    

    And this is my second file from where i call function onClick()
    secondFile.py

    from main import Window
    
    def onClick():
        print("abstract button")
        dj = Window()
        dj.setExpression(str(0))
    

    When i run this my button not working.. when i put this function in main.py file then it is wokking


  • Lifetime Qt Champion

    Hi,

    "dj" lifetime is related to onClick.



  • Iam sorry i dont understand ? What should i do to get it work ?


  • Lifetime Qt Champion

    @Samuel-Bachorik dj is a local variable inside onClick. It is destroyed as soon as onClick finishes. Make dj a variable in secondFile.py or a member variable if onClick is in a class.



  • @Samuel-Bachorik
    Probably make dj a member variable in self. As it stands, dj = Window() creates a Window, but then goes out of scope and so the Window gets destroyed as soon as you exit the onClick() slot.

    However, I suspect there is/may be some confusion here. You create one window = Window in the __main__ scope. Window is a QMainWindow. You then create a new, separate Window in onClick. Why? In normal case your program should have only one QMainWindow, why do you want a second one? If you want another window, why make it a QMainWindow?


Log in to reply