Nominate our 2022 Qt Champions!

Make the TextField text to fit the TextField height

  • Hi,
    I have a problem working on TextField, I have a fixed size for the height and the width of the TextField and I would like that the text displayed in the TextField fit that height.

    Here is the problem that I have (the text in the TextField is the height) :
    alt text

    I have seen fontSizeMode: Text.Fit for Text and I would like something like this but I didn't find the equivalent for TextField, any idea?

  • Moderators

    @Mixlu have you tried:

    font.pixelSize: height


    Should work, if you have a fixed hight for your TextField

  • Moderators

    And if @J-Hilk's suggestion fails, you can use TextMetrics component.

  • @J-Hilk, thanks for your reply

    font.pixelSize: height

    don't work :

    @sierdzio, thanks for your reply
    How could I use TextMetrics ? The idea would be to create many TextMetrics and test if it fits the TextField height ?

  • Moderators

    Hm, you're right, you want something else than the usual case.

    I guess you could cycle different sizes in a loop and arrive at one which fits.

    don't work :

    You probably need to take borders, margins and padding into account. So try something like:

    font.pixelSize: height * .7

  • @sierdzio

    Yes you were right, some padding to take in count here.

    What I have done is

    padding: height*0.1
    font.pixelSize: height - topPadding - bottomPadding

    and it works pretty well :

    Thanks for your help!

  • I faced a very similar problem to this, so this was a very useful item. However, I found that I needed some further tweaks. For some reason, adjusting by the raw padding was not sufficient to ensure the text fitted in the box, so I fudged it by scaling by 0.9:

    font.pixelSize: 0.9 * (height - topPadding - bottomPadding)

    I also decided on a padding to height ratio of 0.15 but that was just my preference.

    One difference I notice between Windows and Linux is that Linux seems to be adding extra padding at the bottom despite the bottomPadding being reported as equal to the topPadding. I see this extra space with and without centred vertical alignment though maybe I saw a marginal improvement with the alignment set.

    Windows: 8a0a5558-4f89-47f9-9eed-bf77edaaddf4-image.png

    Linux: 610cc7ab-f8ff-42d6-bc46-a2d59f6cb195-image.png

    Note the cursor height on Linux. I'm not sure how much one can read into it, but it seems to me that it does not seem to be aware of that space at the bottom of the text.

    A final observation is that the default padding was 6, independent of height (at least for the range I tried). This is pretty big for a moderate sized text field. As a relative newbie, I guess I wouldn't really have expected to have to mess with the default padding on a text field unless I had some special requirement. A lesson learned!

Log in to reply