i have a python class that create a window that includes
where the EditLine will get the userInput that is a path for folder.
the problem is that once i run the script it enter in infinite loop.
'''
1- import the libraries from the converted file
2- import the converted file
'''
from PyQt5 import QtCore, QtGui, QtWidgets
import pathmsgbox
import os
import pathlib
class path_window(pathmsgbox.Ui_PathMSGbox):
def __init__(self,windowObject ):
self.windowObject = windowObject
self.setupUi(windowObject)
self.checkPath(self.pathEditLine.text())
self.windowObject.show()
def checkPath(self, pathOfFile):
folder = self.pathEditLine.text()
while os.path.exists(folder) != True:
print("the specified path not exist")
folder = self.pathEditLine.text()
return folder
'''
get the userInput from the EditLine
'''
'''
def getText(self):
inputUser = self.pathEditLine.text()
print(inputUser)
'''
'''
function that exit from the system after clicking "cancel"
'''
def exit():
sys.exit()
'''
define the methods to run only if this is the main module deing run
the name take __main__ string only if its the main running script and not imported
nor being a child process
'''
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
PathMSGbox = QtWidgets.QWidget()
pathUi = path_window(PathMSGbox)
pathUi.pathCancelBtn.clicked.connect(exit)
sys.exit(app.exec_())
The problem here is that you're calling checkPath()
in the class initialization.
checkPath()
read the path one time, and then start to evaluate if that path is valid 'forever'. This while
loop running may even prevent the software to be able to effectively read again the text from self.pathEditLine
.
Usually it's better to connect each function to an event:
For doing any of these, you have to connect one of these events to the function:
button event:
self.btnMyNewButton.clicked.connect(checkPath)
text changing event:
self.pathEditLine.textChanged.connect(checkPath)
enter button event:
self.pathEditLine.returnPressed.connect(checkPath)
This means that you have to substitute one of the previous lines with the line where you call the checkPath()
function in the initialization:
def __init__(self,windowObject ):
self.windowObject = windowObject
self.setupUi(windowObject)
self.pathEditLine.textChanged.connect(checkPath)
self.windowObject.show()
you also have to remove the pathOfFile
argument from checkPath(self, checkPath)
because you are not using it.
Since we decided a different behaviour for our checkPath()
function, we no longer need a while
loop: we will be reading the user input each time the event
occurs, evaluate the user input, return the user input if we like it or return False
if we don't:
def checkPath(self):
folder = str(self.pathEditLine.text())
if os.path.exists(folder):
print '%s is a valid folder' % folder
return folder
else:
print '%s is NOT a valid folder' % folder
return False