I need to know Button text length in pixels. How to do that ?

  • This question must be shared with StackOverflow. Apr 18 '15 at 15:08

Look at the following code snippet:

import QtQuick 2.0
import Ubuntu.Components 0.1

MainView {
    width: 160
    height: 160

    Button {
        id: my_button
        Text {
            id: my_text
            anchors {centerIn: parent }
            text: my_button.width + " x " + my_button.height
        Component.onCompleted: console.log(my_text.width)

The default text property of a button is just a string and will inherit the style applied on the Button component.

To get access to the string length in pixel, use instead a dedicated Text element inside your button so that you can access its pixel width like this: my_text.width.

Running the above code with qmlscene logs 41.953125 on the standard output for the string "80 x 40"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.