Search code examples
pythonpython-3.xpyqtpyqt4qtextedit

Python 3 key-sorted dict function not working correctly with PyQt4


I have a function which is supposed to sort a dict and print the result in a QTextEdit box - "ADtext" in the gui window.

Example dict:

lunch = {5: "14:00-16:00",27: "12:00-13:00", 13: "12:00-13:00"}

function:

    def example(self):
       keys= list(lunch.keys())
       keys.sort()
       for key in keys:
           self.ADtext.setText("({} => {})".format(key, lunch[key]))

However in the gui QTextEdit -"ADtext" box only one of the pairs is shown (always the same).

The function works without problems if I print the result in cmd (not in the QTextEdit box):

print ("({} => {})".format(key, lunch[key]))

Solution

  • You have to use append() since setText() removes the previous text:

    def example(self):
       self.ADtext.clear() # clean the previous text
       keys= list(lunch.keys())
       keys.sort()
       for key in keys:
           self.ADtext.append("({} => {})".format(key, lunch[key]))