Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dynamically change label texts in pyqt5 by passing a text widget into a function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading