Check for truncation of displayed text (Qt)

Last edited on

This example shows how to check whether the text shown in a widget (in this case a line edit) has been truncated (e.g., because it is wider than the width of the widget).

The checkTruncation() function compares the widget’s actual width (from its width property), with the number of pixels needed to display the entire text (returned by the requiredWidth() function), and calls Squish’ function if the actual width is less than the required width.

def main():
    nameLineEdit = waitForObject(":First Name_QLineEdit")
    checkTruncation(nameLineEdit) # line edit is empty so shouldn't fail
    type(nameLineEdit, "The quick brown fox jumps over the lazy dog. " * 2)
    checkTruncation(nameLineEdit) # line edit is too full so should fail

def checkTruncation(widget):
    text = str(widget.text)
    if widget.width < requiredWidth(widget, text):
        name = objectMap.symbolicName(widget)"GUI object %s has truncated text: '%s'" % (name, text))

def requiredWidth(widget, text):
    fm = QFontMetrics(widget.font)
    return fm.boundingRect(QString(text)).width