Search code examples
qmlqt6

Is it possible to know default size of the QML Control?


Is it possible to know default size (height) of the QML Control? Something like QWidget::sizeHint()...

I want to set implicitHeight of the TextField to be 8mm, this is fine on desktops, but on Android 8mm is not enough, so I want something like:

implicitHeight: Math.max( minimumCtrlHeight (8mm), defaultHeight )

Maybe this can be done with another approach? Thanks.

Maybe in QML it's possible to use something like #ifdef to set implicitHeight on desktops but not on mobile?


Solution

  • You can do something like this:

    import QtQuick 2.15
    import QtQuick.Controls 2.15
    
    Rectangle {
        id: root
        anchors.centerIn: parent;
        function preffredButtonHeight(parent_: Item) {
            if (Qt.platform.os == "android" || 
                   Qt.platform.os == "wasm" || 
                   Qt.platform.os == "ios") {
                return Math.max(parent_.height / 25, 88, implicitHeight);
            } else {
                return Math.max(parent_.height / 25, 50, implicitHeight);
            }
        }
        Button {
            anchors.centerIn: parent;
            text: "platform is: " + Qt.platform.os
            height: preffredButtonHeight(parent)
        }
    }
    

    This could be done more declaratively though I think it would be more messy. You can also implement that JS function in C++, That is what I would do.

    Note that you can use Screen.desktopAvailableHeight if you don't want to use parent or use both of them them...

    import QtQuick 2.15
    import QtQuick.Controls 2.15
    import QtQuick.Window 2.2
    
    Rectangle {
        id: root
        anchors.centerIn: parent;
        function preffredButtonHeight(parent_: Item) {
            if (Qt.platform.os == "andriod" || "wasm" || "ios") {
                return Math.max(Screen.desktopAvailableHeight / 25, 88, implicitHeight);
            } else {
                return Math.max(Screen.desktopAvailableHeight / 25, 50, implicitHeight);
            }
        }
        Button {
            anchors.centerIn: parent;
            text: "platform is: " + Qt.platform.os
            height: preffredButtonHeight(parent)
        }
    }