1

I'm fairly new to Python and I have a question about passing a variable from one function to antother (in a PyQt script).

This is my script:

from PyQt4 import QtCore, QtGui
import analysefuncties
import os

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(581, 631)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.listWidget_vars = QtGui.QListWidget(self.centralwidget)
        self.listWidget_vars.setGeometry(QtCore.QRect(10, 40, 211, 531))
        #self.listWidget_vars.setAcceptDrops(True)
        self.listWidget_vars.setDragEnabled(True)
        self.listWidget_vars.setDragDropMode(QtGui.QAbstractItemView.DragOnly)
        self.listWidget_vars.setObjectName(_fromUtf8("listWidget_vars"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 10, 101, 20))
        self.label.setObjectName(_fromUtf8("label"))
        self.listWidget_2 = QtGui.QListWidget(self.centralwidget)
        self.listWidget_2.setGeometry(QtCore.QRect(300, 40, 256, 41))
        self.listWidget_2.setAcceptDrops(True)
        self.listWidget_2.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
        self.listWidget_2.setObjectName(_fromUtf8("listWidget_2"))
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(300, 540, 141, 28))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(470, 540, 90, 28))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 581, 26))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuBestand = QtGui.QMenu(self.menubar)
        self.menuBestand.setObjectName(_fromUtf8("menuBestand"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionSelecteer_bestand = QtGui.QAction(MainWindow)
        self.actionSelecteer_bestand.setObjectName(_fromUtf8("actionSelecteer_bestand"))
        self.actionSluit_programma = QtGui.QAction(MainWindow)
        self.actionSluit_programma.setObjectName(_fromUtf8("actionSluit_programma"))
        self.menuBestand.addAction(self.actionSelecteer_bestand)
        self.menuBestand.addAction(self.actionSluit_programma)
        self.menubar.addAction(self.menuBestand.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #bind functies aan knoppen
        self.actionSelecteer_bestand.triggered.connect(self.OpenBestand)
        self.pushButton.clicked.connect(self.StartAnalyse)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.pushButton.setText(_translate("MainWindow", "Start analyse", None))
        self.pushButton_2.setText(_translate("MainWindow", "Reset", None))
        self.menuBestand.setTitle(_translate("MainWindow", "Bestand", None))
        self.actionSelecteer_bestand.setText(_translate("MainWindow", "Selecteer bestand", None))
        self.actionSluit_programma.setText(_translate("MainWindow", "Sluit programma", None))

    def OpenBestand(self):
        bestand = str(QtGui.QFileDialog.getOpenFileName(None, "Selecteer dataset"))

    def StartAnalyse(self):
        # use 'bestand' from other function, e.g.:
        dataset = bestand
        print dataset

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

In "OpenBestand()" I let the user select a file. I want to do something with this file (the path+name) in another function: StartAnalyse. But I cannot do it like the way it is in the script above.

What I can do is returning the variable from OpenBestand() and call it from StartAnalyse():

def OpenBestand(self):
    bestand = str(QtGui.QFileDialog.getOpenFileName(None, "Selecteer dataset"))
    return bestand

def StartAnalyse(self):

    dataset = OpenBestand()
    print dataset

But now everytime I click the button that is connected with 'StartAnalyse' the function 'OpenBestand()' runs and I don't want that. That function belongs to another button.

So I came up with two solutions. Solution 1: make the variable 'bestand' in OpenBestand() global:

def OpenBestand(self):
    global bestand
    bestand = str(QtGui.QFileDialog.getOpenFileName(None, "Selecteer dataset"))


def StartAnalyse(self):
    dataset = bestand
    print dataset # and do stuff with variable (put it in another function)

Solution 2: put path and filename from OpenBestand() in a temporary file and read this file in StartAnalyse() (and os.remove('temfile.txt') it when closing the app):

def OpenBestand(self):
    bestand = str(QtGui.QFileDialog.getOpenFileName(None, "Selecteer dataset"))

    tempf = open('tempfile.txt','w')
    tempf.write(bestand)
    tempf.close()

def StartAnalyse(self):

    tempf = open('tempfile.txt','r')
    dataset = tempf.read()
    tempf.close()

    print dataset

I've read on this forum that declaring global variables is dangerous. So is solution 2 better? Or is there an alternative?

3
  • 1
    why don't you use self ? self.__bestand = str(QtGui.QFileDialog.getOpenFileName(None, "Selecteer dataset")). Then self.__bestand is visible from the other method. That's what OOP is for. Commented Mar 24, 2017 at 9:18
  • Thank you. This works! Can you give me some good documents about OOP? (for beginners...) Commented Mar 24, 2017 at 9:22
  • 1
    you're already doing OOP when using Qt. You just didn't know it. I cannot really recommend any document. But lookup "python object oriented programming" you'll find stuff Commented Mar 24, 2017 at 9:28

1 Answer 1

1

You should avoid global variables when you can. Here, you can.

Since you're in the same object (identified as self in instance methods), the best way is probably to use a "private" (name-mangled) member to store the value (so it's not easily visible from outside the object), and recall it from the other method.

In __init__(self) add self.__bestand = None so it is defined

Then in your OpenBestand method, assign it:

self.__bestand = str(QtGui.QFileDialog....

and in your StartAnalyse, test to see if it's properly set and use it:

if self.__bestand: # empty or None: won't pass
   # do something
   print(self.__bestand)
Sign up to request clarification or add additional context in comments.

4 Comments

Are the two underscores (self.__bestand) necessary? I tried it without them and that works to. Is it a convention or something?
Kind of. It hides the attribute from the outside of the object.
Use one underscore, though. Two is generally considered reserved for Python itself.
@Harvey no. Using 2 underscores before and after is reserved for Python. 2 underscores before means name-mangled so parent & child class can define the same member without it being shared/overwritten

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.