I want to dynamically edit the content of a QLineEdit text, by passing the Widget to a function that initiates a filedialoge. The text of the passed widget shall then be set to the selected file. Obviously I do not want to create a function for each QLineEdit Widget.
This is the current state (which is obviously not working).
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class UserInterface(QWidget):
def __init__(self, *args, **kwargs):
super(UserInterface, self).__init__(*args, **kwargs)
self.layout = QFormLayout()
self.button_test_1 = QPushButton("Select File")
self.line_test_1 = QLineEdit("Select File")
self.button_test_1.clicked.connect(lambda: self.select_file(self.line_test_1))
self.layout.addRow(self.button_test_1,self.line_test_1)
self.button_test_2 = QPushButton("Select File")
self.line_test_2 = QLineEdit("Select File")
self.button_test_2.clicked.connect(lambda: self.select_file(self.line_test_2))
self.layout.addRow(self.button_test_2,self.line_test_2)
self.setLayout(self.layout)
def select_file(self,line):
fileName = QFileDialog.getOpenFileName(self,"Choose File",directory="D:\\",filter="*.json *.csv")
self.line.setText(fileName)
def main():
app = QApplication(sys.argv)
controller = UserInterface()
controller.show()
sys.exit(app.exec_())
main()
Currently it results in an error als "self.line" does not exist.
In the end I want to be able to pass self.line_test_[n](or any other name) to my select_file function and set the text of the passed Wigdet within the function.
You just need to remove self keyword for it to work:
def select_file(self, line):
fileName = QFileDialog.getOpenFileName(self, ,"Choose File",directory="D:\\",filter="*.json *.csv")[0] # Make sure to use [0] here to get the file name.
line.setText(fileName) # Remove self here
However, the setText will break right away since the value of fileName is not string but a tuple. Therefore you need to put [0] after ..."*.json *.csv")