【问题标题】:Binding to a QML widget's rendered height绑定到 QML 小部件的渲染高度
【发布时间】:2020-04-29 10:47:51
【问题描述】:

假设我有一个文本字段和一个按钮。我想将按钮的宽度和高度设置为文本字段的呈现高度,但它不起作用。

import QtQuick 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.3
import QtQuick.Window 2.10

Window {
    id: window
    visible: true
    width: 640
    height: 200
    color: "#f0eded"
    title: qsTr("Hello World")

    RowLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter

        TextField {
            id: txtPassword
            text: qsTr("Text Field")
            font.pointSize: 22
        }

        Button {
            id: btnSubmit
            width: txtPassword.height
            height: txtPassword.height
            text: qsTr("»")
        }
    }
}

按钮似乎忽略了与文本字段高度的绑定。我的理论是,由于没有明确设置此属性,QML 不知道分配给按钮的宽度/高度。

采用文本字段的实际呈现高度的正确方法是什么?

【问题讨论】:

    标签: qt layout qml


    【解决方案1】:

    如果你使用布局你不应该使用宽度或高度,如果你想获得相同的高度你必须使用implicitWidthimplicitHeight,如果你想让item占据行的高度那么你必须使用Layout.fillHeight: true。宽度也一样。

    import QtQuick 2.0
    import QtQuick.Layouts 1.3
    import QtQuick.Controls 2.3
    import QtQuick.Window 2.10
    
    Window {
        id: window
        visible: true
        width: 640
        height: 200
        color: "#f0eded"
        title: qsTr("Hello World")
    
        RowLayout {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
    
            TextField {
                id: txtPassword
                text: qsTr("Text Field")
                font.pointSize: 22
            }
    
            Button {
                id: btnSubmit
                implicitHeight: txtPassword.implicitHeight // or Layout.fillHeight: true
                implicitWidth: implicitHeight
                text: qsTr("»")
            }
        }
    }
    

    或者,您可以使用Row,而不是使用RowLayout

    import QtQuick 2.0
    import QtQuick.Layouts 1.3
    import QtQuick.Controls 2.3
    import QtQuick.Window 2.10
    
    Window {
        id: window
        visible: true
        width: 640
        height: 200
        color: "#f0eded"
        title: qsTr("Hello World")
    
        Row {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            spacing: 5
    
            TextField {
                id: txtPassword
                text: qsTr("Text Field")
                font.pointSize: 22
            }
    
            Button {
                id: btnSubmit
                width: txtPassword.height
                height: txtPassword.height
                text: qsTr("»")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      相关资源
      最近更新 更多