Error when trying to take the Input from a file path and pass it to an other function using PyQt5

Viewed 59

I'd like to pass the path of a file that I select from my pc

def openFileNameDialog(self):
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
    if fileName:
        print(fileName)

button = QPushButton('Louvain Algorithm', self) button.setToolTip('This is an example button') button.move(50,300) 
button.clicked.connect(self.on_click_louvain)

into an other function

def on_click_louvain(self,fileName): 
    # Replace this with your networkx graph loading depending on your format !

    G = nx.read_gml(str(fileName,))

but i get this error

FileNotFoundError: [Errno 2] No such file or directory: 'False'

Any ideas for the solution??

1 Answers

You have several misconceptions:

  • The variable "fileName" is local, so it cannot be accessed in other methods.

  • The variable "fileName" will not be passed magically as an argument of another method. Also by default the clicked signal has a Boolean associated and that is the one that is generating the error.

The solution is to store the variable as an attribute of the class and then access through the object:

def openFileNameDialog(self):
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
    self.fileName = fileName
def on_click_louvain(self): 
    # Replace this with your networkx graph loading depending on your format !
    G = nx.read_gml(self.fileName)
Related