Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qt Quick Controls 2 TabBar/TabButton autosize to button text width



  • Is there a way that the Qt Quick Controls 2 TabBar/TabButton can auto size to the button text - it seems the current implementation wastes a lot of space even if padding is set to 0.
    Thanks.



  • TabBar distributes the space equally by default, but respects the widths if TabButtons have it explicitly specified. To make buttons to retain their implicit width, you could do:

    TabBar {
        TabButton {
            text: "Foo"
            width: implicitWidth // <==
        }
        ...
    }
    


  • Setting a width works but then I need to manually calculate the width for every button in the TabBar - Is there a way to access the size of the text in the button?



  • Is it not what you get with implicit width? The implicit width of the button equals to the implicit width of the content item + left padding + right padding. For the built-in styles, the content item is a Text element.

    PS. If you still need to calculate the width of a specific text string, QML TextMetrics (http://doc.qt.io/qt-5/qml-qtquick-textmetrics.html) can do that.



  • if I set width: implicitWidth the text does not show - Looking at the source it should be as you pointed out:

    implicitWidth: Math.max(background ? background.implicitWidth : 0, contentItem.contentWidth + leftPadding + rightPadding)

    But it seems the value is 0



  • I can't test right now, but I suspect it could be because it's using contentWidth instead of implicitWidth. Feel free to report a bug. This is something we should ensure that it works and even make it easily configurable.

    Does it resize to contents if you do:

    TabButton {
        width: contentItem.implicitWidth + leftPadding + rightPadding
    }
    

    ?



  • Yes, that does the trick! Now it's sizing according to the text width.
    Thanks a lot for your help - I will file a bug report
    Thanks again!


Log in to reply