Search code examples
pythonfunctionpyqtsignals-slots

Python - how to use the value of a variable inside a function that is called when a button is clicked


I have a piece of python code like this:

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

    --snip--        

        self.ui.pushButton.clicked.connect(self.selectFile)
        someParameter = someFunction(self.filename) # (1)

    def selectFile(self):
        self.ui.lineEdit.setText(QtGui.QFileDialog.getOpenFileName())
        self.filename = self.ui.lineEdit.text() # I want to use "filename" variable in (1)

    --snip--

I want to catch the name of the file which is selected by QFileDialog and do two things; firstly, show the address of the file in a lineEdit widget and secondly, store the address of the file in a variable so I can use it later on the rest of the process. How should I do that, and what is the proper way?


Solution

  • It seems you are not accustomed with object oriented programming. In object oriented programming, there is a member and method in a Class.

    In your case you should define member like this so that you can handle it later. So you should learn about what member is in object oriented programming.

    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.filename = ""
            self.someParameter = None
    
        --snip--        
    
            self.ui.pushButton.clicked.connect(self.selectFile)
    
        def setParameter(self):
            self.someParameter = someFunction(self.filename)
    
        def selectFile(self):
            self.filename = QtGui.QFileDialog.getOpenFileName()
            self.ui.lineEdit.setText(self.filename)
            self.setParameter()
    
        --snip--
    

    Edited

    Here is some sample code which use QFileDialog.getOpenFileName. Try this.

    from PyQt5.QtWidgets import QWidget, QPushButton, QFileDialog, QVBoxLayout, QApplication
    from PyQt5 import QtGui
    
    class my_ui(QWidget):
        def __init__(self, parent=None):
            super(my_ui, self).__init__()
            self.filename = ""
            self.button1 = QPushButton("show dialog", parent)
            self.button2 = QPushButton("do something", parent)
            self.button1.clicked.connect(self.show_dialog)
            self.button2.clicked.connect(self.do_something)
            self.layout = QVBoxLayout()
            self.layout.addWidget(self.button1)
            self.layout.addWidget(self.button2)
            self.setLayout(self.layout)
        def show_dialog(self):
            self.filename = QFileDialog.getOpenFileName()
            print("filename updated: '%s'"%str(self.filename)) 
        def do_something(self):
            print("filename = '%s'"%str(self.filename)) 
    
    app = QApplication([])
    sample_ui = my_ui()
    sample_ui.show()
    app.exec_()