设置Button组件固定宽度

问题描述 投票:0回答:1

我从 QML 开始。我尝试构建一个简单的组件(用于聊天窗口),它是一个包含文本字段和按钮的水平灰色矩形。 矩形应占据其父级的整个水平空间。右侧的按钮应该有一个固定的,文本字段占据剩余空间。

问题:我无法将按钮宽度设置为固定值。我尝试设置宽度属性,但这没有任何效果。

这是我到目前为止的代码:

应用程序.qml:

import QtQuick 6.2
import QtQuick.Window 6.2
import Test1

Window {
    width: 600
    height: 800

    visible: true
    title: "Test1"

    Screen01 {
        id: mainScreen
    }
}

Screen01.ui.qml:

import QtQuick 6.2
import QtQuick.Controls 6.2
import QtQuick.Layouts 6.2
import Test1

Rectangle {
    id: rectangle
    height: 50
    anchors.left: parent.left
    anchors.right: parent.right
    color: "#555";

    RowLayout {
        id: chatInputLayout
        anchors.fill : parent

        TextField {
            id: chatInputField
            placeholderText: "Write something ..."
            Layout.fillWidth: true
            Layout.margins: 5
        }

        Button {
            id: chatSendButton
            width: 200
            //Layout.fillWidth: true
            text: "send"
            Layout.topMargin: 5
            Layout.rightMargin: 5
            Layout.bottomMargin: 5
            Layout.leftMargin: 0
            Connections {
                onClicked: function() {
                    console.log("text", chatInputField.text)
                }
            }
        }
    }
}
qt qml
1个回答
0
投票

正如 smr 已经评论的那样,您可以使用

Layout.preferredWidth
来实现按钮的静态宽度。共享文档还提到
implicitWidth
也可以使用,我在下面的代码片段中注释掉了。

如果首选宽度为-1,它将被忽略,布局将 请改用implicitWidth。

Rectangle {
    id: rectangle
    height: 50
    anchors.left: parent.left
    anchors.right: parent.right
    color: "#555"

    RowLayout {
        id: chatInputLayout
        anchors.fill: parent
        anchors.margins: 5
        spacing: 5

        TextField {
            id: chatInputField
            placeholderText: qsTr("Write something ...")
            Layout.fillWidth: true
        }

        Button {
            id: chatSendButton
            width: 200
            //implicitWidth: chatSendButton.width
            Layout.preferredWidth: chatSendButton.width
            text: qsTr("Send")

            Connections {
                function onClicked() {
                    console.log("Send.onClicked", chatInputField.text)
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.