0

I need to subclass a PyQt5 QLineEdit so that it has an index, such that I could access it by:

    stringvariable = LineEdit(0).text()
    stringvariable = LineEdit(1).text()
    stringvariable = LineEdit(2).text()

Is this possible?

nlgootee
  • 35
  • 8

1 Answers1

1

Why don't you make a list of your LineEdits?

mylist = [QLineEdit(), QLineEdit(), QLineEdit()]
    
index = 0
string = mylist[index].text()
print(string)

Or, if you really need to make a subclass

class MyLineEdit(QLineEdit):
    all_instances = {}
    def __init__(self, index, *args, **kwargs):
        super(MyLineEdit, self).__init__(*args, **kwargs)  # call to superclass
        MyLineEdit.all_instances[index] = self  # add this instance to MyLineEdit.all_instances
    
def LineEdit(index):
    return MyLineEdit.all_instances[index]

To use it, you can simply do:

# Make an instance
edit = MyLineEdit(123)

string = LineEdit(123).text()
# which is equivalent to using
string = edit.text()
MrP01
  • 1,425
  • 13
  • 20
  • I don't need the index of a list. I need a subclassed LineEdit with an index attribute that I can set when the object is created. I would like to be able to access it with LineEdit(index).text() – nlgootee May 01 '16 at 13:29
  • @nigootee like this? – MrP01 May 01 '16 at 15:31
  • 1
    Let me clarify my previous comment. Based on the last line of your code, it looks like what I want, but I don't understand your code. Is all_instances = {} there only to create the index number? – nlgootee May 01 '16 at 15:34
  • All_instances is a static variable of MyLineEdit, which means that it is not bound to an instance, it is the same for the whole class object. So whenever You make an instance of MyLineEdit, that instance is stored in MyLineEdit.all_instances (a dictionary) with the key being an index (in this case 123) and the value being the instance (self). And whenever you want to retrieve a MyLineEdit by its index, you call the _function_ LineEdit. – MrP01 May 02 '16 at 18:03
  • I create an instance of MyLineEdit and place it on a form and add it to a dictionary. When text is added to the LineEdit(123) on the form, is the text retrieved when I access the MyLineEdit(123) in the dictionary? – nlgootee May 03 '16 at 15:48
  • Would you please consider updating your question and putting some code on it? I don't understand what you want to know. – MrP01 May 06 '16 at 12:36
  • I am not going to be able to work on this for the next week, but I will work with the code that you gave me and get back to you as soon as I can. Thanks for your help. – nlgootee May 07 '16 at 13:38