Home > front end >  How do I make variables available outside of functions in Python (and Qt)
How do I make variables available outside of functions in Python (and Qt)

Time:12-24

I have a newbie Python QT5 Designer question. Read a lot of info here on variables not being available outside their respective functions in python, but most examples return a result to the called function, not from another triggered event. I have probably missed something, as this is very easy to do in other languages. As you can see in my example, the functions are called from button clicks on the gui, so the variable for the starttime needs to be available when the stop button is clicked. This example should simply subtract one time from another and display the results in a label on a Qt5 Window. Any help would be appreciated.

import sys
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import*
from PyQt5.uic import loadUi
from PyQt5.QtCore import QTime, QDateTime, Qt
qtgui_file  = r"example.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtgui_file)
class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self,parent=None):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.pbstart.clicked.connect(self.setstarttime)
        self.pbstop.clicked.connect(self.setstoptime)
    def setstarttime(self):
        self.pbstart.setEnabled(False)
        self.pbstop.setEnabled(True)
        starttime = QTime.currentTime()
        self.lblstart.setText(starttime.toString(Qt.DefaultLocaleLongDate))
    def setstoptime(self):
        self.pbstart.setEnabled(True)
        self.pbstop.setEnabled(False)
        endtime = QTime.currentTime()
        self.lblstop.setText(endtime.toString(Qt.DefaultLocaleLongDate))
#..code in here to subtract endtime from startime stored in timediff variable
#?????
        timediff = "...dummy string as starttime is not defined in this function"
        self.lbltimediff.setText(timediff)
        
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())```

CodePudding user response:

My suggestion is to either make the variables global with the global key word.

def setstarttime(self):
    self.pbstart.setEnabled(False)
    self.pbstop.setEnabled(True)
    global starttime
    starttime = QTime.currentTime()
    self.lblstart.setText(starttime.toString(Qt.DefaultLocaleLongDate))

OR

You just define them as class variables like

self.starttime = datetime.datetime.min()

And then use the variable in whatever function you want.

  • Related