0

I am having problems replacing the value of global variables using buttons in Qt5.

I am relatively new to Python and I am sure I am missing something trivial, but I couldn't find the solution.

Below you see an example of a GUI where the button "Move down" moves the position of a QLineEdit towards the bottom. The problem is that I can only move it once to a fixed new position. I cannot continue to move it downward by pressing the button multiple times, because I am not able to continuously update the value of the global variable YY. In fact, when the value of YY gets printed after pressing the button, it shows always the same value.

Returning the new YY value from the function doesn't do the trick, because I am not able to associate the new value to the variable by connecting the the signal.

Thanks in advance!

    import sys
    import PyQt5.QtCore
    from PyQt5.QtCore import Qt
    import PyQt5.QtWidgets as qt5
    from PyQt5.QtWidgets import QApplication, QVBoxLayout, QLabel, QSlider, QLineEdit, QWidget, QLCDNumber, QSlider, QVBoxLayout
    from PyQt5.QtGui import QIcon
    
    XX = 800
    YY = 80

    def MoveDown(x):
        newYY = x + 60
        qle.move(XX, newYY)
        return UpdateYY(newYY)

    def UpdateYY(y):
        YY = y
        print(YY)

    #############################################

    app =  PyQt5.QtWidgets.QApplication(sys.argv)

    w = PyQt5.QtWidgets.QMainWindow()
    w.resize(1280, 480)
    w.move(300, 300)

    MainWindow = PyQt5.QtWidgets.QWidget()

    vboxlayout = qt5.QVBoxLayout()
    hboxlayout = qt5.QHBoxLayout()
    vboxlayout.addLayout(hboxlayout)
    MainWindow.setLayout(vboxlayout)

    qle = QLineEdit(MainWindow)
    qle.move(XX, YY)
    MoveButton = qt5.QPushButton("Move down")
    MoveButton.clicked.connect(lambda: MoveDown(YY))
    vboxlayout.addWidget(MoveButton)

    w.setCentralWidget(MainWindow)

    w.show()

    app.exec()
  • 1
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Passerby Nov 04 '21 at 11:57

1 Answers1

0

You need to clarify that it is a global variable.

You can do that by adding

def UpdateYY(y):
        global YY # This will tell python it should use the global scope of YY
        YY = y
        print(YY)
ziarra
  • 137
  • 6