Question

I am trying to position buttons (TExtButton) using the ExtPascal library (wrappers round ExtJS) in Lazarus. I want to set the width of the buttons based on the text and font of the button. I have tried various combinations of GetWidth and JSExpression and ExtUtilTextMetrics, but the answer that comes back is something like -420,000.

It may be relevant that I was unable to get the font to change using calls like this:

JSCode('style:{"font-size":"'+ FontSize +'px","font-family":"Tahoma"}');

but the only effect I could get that way was that the button was higher if I set the font big enough, but the text of the button was rendered in the original small font.

So I resorted to putting the style into the string that gets passed to the Text property of the buttons, using this expression:

result := '<b style="font-size:1.4em;font-family=sans-serif;color:rgb(14,63,138);">' + s + '</b>'

Can anyone help me work out the exact text width?

TIA Mark

No correct solution

OTHER TIPS

At first, I don't know ExtPascal nor Lazarus.

I believe the solution is pretty simple. It is possible to do it with JavaScript only.

The steps: 1. Create a hidden div.

When you need the width of some text, 1. set text, fontSize and fontFamily of the hidden div. 2. set hidden div to visible 3. get width of div. 4. set div back to hidden.

In code:

<html>
<head>
    <script>
        function getWidth(text, fontSize, fontFamily) 
        {
            var element = document.getElementById('ruler');

            element.style.fontSize = fontSize;
            element.style.fontFamily = fontFamily;
            element.style.display = "inline";
            element.innerHTML = text;

            var width = element.offsetWidth;
            document.getElementById('width').innerHTML = width;
        }
    </script>
    <style>
        div#ruler
        {
            display : none;
        }
    </style>
</head>
<body onload="getWidth('Test', '13', 'Verdana');">
    <div id="ruler"></div>
    <div id="width"></div>
</body>
</html>

Its also possible with ExtJs, but this is the easiest way to get the width of text.

Hope this helps.

In ExtJS use a helpful TestMetrics class like this:

var textWidth = 
  Ext.util.TextMetrics.measure(
    extTextfield.getEl().dom, 
    text).
  width;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top