Search code examples
pythonpython-3.xpyqtpyqt5qlistwidget

Printing string is different from adding to list, why?


I have the following code:

if len(itemName) < 31:
                while len(itemName) < 31:
                    itemName = itemName+"-"
            itemName = itemName + self.convert_size(info.st_size)
            while len(itemName) < 48:
                itemName = itemName+"-"
            itemName = itemName + datetime.fromtimestamp(info.st_ctime).strftime("%d/%m/%Y %H:%M")
            print(itemName)

which prints this: enter image description here

which is exactly what I want, all sizes and dates starting at the same positions for all files (aligned).

Now I add this line after the print statement: self.file_list.addItem(itemName)

Which in Qt is basically adding an item to a list. Here's a screenshot of how it looks on the list: enter image description here

As you can see sizes and dates are not aligned/starting at same positions.

My questions is why an how can I fix the problem? It prints it out just fine but when adding to a QListWidget, it does not look the same.

Thanks in advance!


Solution

  • This is a matter of the font that Qt is using, it is using a font that is not monospace, i.e: different characters have different sizes, to use a monospace font that displays all characters with the same size, change the Qt font to consolas (preferably) or Courier New or any other monospace font.