Qt Quick:不显示矩形

时间:2018-07-12 11:04:23

标签: qt qml qt-quick

我正在创建一个基本的登录表单,但是矩形未显示。请忍受我!

main.qml:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 400
    height: 600

    LoginForm {
        anchors.centerIn: parent
        //height: 300
        //width: 300
    }

}

LoginForm.ui.qml:

import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Item {

    Rectangle {
        color: "#E8E8E8"
        radius: 5
        anchors.centerIn: parent
        anchors.fill: parent
        width: childrenRect.width
        height: childrenRect.height

        GridLayout {
            id: "grid_layout"
            flow: GridLayout.TopToBottom
            anchors.centerIn: parent
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.topMargin: 12
            anchors.bottomMargin: 12
            anchors.leftMargin: 12
            anchors.rightMargin: 12

            Text {
                id: "log_in_label"
                text: "Log In"
                font.pointSize: 15;
            }

            Text {
                id: "username_label"
                text: "Username:"
                font.pointSize: 8
            }

            TextField {
                id: "username_input"
                Layout.columnSpan: 2
                font.pointSize: 8
            }

            Text {
                id: "password_label"
                text: "Password:"
                font.pointSize: 8
            }

            TextField {
                id: "password_input"
                Layout.columnSpan: 2
                font.pointSize: 8
            }

            Button {
                text: "Sign in"
            }
        }
    }
}

我对Qt Quick完全陌生,我不明白为什么它不起作用,但是当我取消注释“ height:300”和“ width:300”时,它神奇地起作用了。为什么会这样,以及我应该如何克服这个问题,因为我不想手动定位它们,所以我宁愿使用比率和布局。

2 个答案:

答案 0 :(得分:0)

您什么都看不到的原因是:

在您的LoginForm.ui.qml中,您有一个Item,由Rectangle填充

Item { // This Item has no size unless you specify it, when instantiating it (uncomment width and height)

    Rectangle {
        color: "#E8E8E8"
        radius: 5
        anchors.centerIn: parent 
        anchors.fill: parent // This will fill the Item. As long as you don't specify a size, it will be invisibile.
        width: childrenRect.width // This conflicts with the anchors. It will be ignored.
        height: childrenRect.height // This conflicts with the anchors. It will be ignored.

        [...]
    }
}

当您未从外部指定尺寸时,可以将implicitWidth/Height的{​​{1}}设置为应具有的尺寸。

Item

答案 1 :(得分:-1)

只需删除LoginForm.ui.qml中的外部项{}