Qt QML 将子属性绑定到父属性

  • 本文关键字:属性 绑定 QML Qt qt qml
  • 更新时间 :
  • 英文 :


我想通过子元素"mainLayout"的最小宽度和高度将应用程序窗口设置为最小宽度和高度。我在父 QML 应用程序窗口中使用"mainLayout"属性时遇到问题。我试图通过制作别名来使属性可见。不确定这是否是正确的解决方案。它不起作用。但是当我运行时也没有错误。

我的代码如下所示:

主.qml

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
ApplicationWindow {
visible: true
width: 1500
height: 1200
property int margin: 11
minimumWidth: serial.mainLayout.minimumWidth + 2 * margin //this one is not working
minimumHeight: serial.mainLayout.minimumHeight + 2 * margin //this one is not working

Serial {
id: serial
anchors.fill: parent
}
}

Serial.qml

import QtQuick 2.7
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import io.qt.serialComm 1.0
Item {
anchors.fill: parent
id: item
property alias mainLayout: mainLayout
ColumnLayout {
id: wrapper
width: parent.width/2
height: parent.height/2
ColumnLayout {
id: mainLayout
anchors.fill: parent
anchors.margins: margin
GroupBox {
id: rowBox
title: "Row layout"
Layout.fillWidth: true
RowLayout {
id: rowLayout
anchors.fill: parent
TextField {
placeholderText: "This wants to grow horizontally"
Layout.fillWidth: true
}
Button {
text: "Button"
}
}
}
GroupBox {
id: gridBox
title: "Grid layout"
Layout.fillWidth: true
GridLayout {
id: gridLayout
rows: 3
flow: GridLayout.TopToBottom
anchors.fill: parent
Label { text: "Line 1" }
Label { text: "Line 2" }
Label { text: "Line 3" }
TextField { }
TextField { }
TextField { }
TextArea {
text: "This widget spans over three rows in the GridLayout.n"
+ "All items in the GridLayout are implicitly positioned from top to bottom."
Layout.rowSpan: 3
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}
TextArea {
id: t3
text: "This fills the whole cell"
Layout.minimumHeight: 30
Layout.fillHeight: true
Layout.fillWidth: true
}
GroupBox {
id: stackBox
title: "Stack layout"
implicitWidth: 200
implicitHeight: 60
Layout.fillWidth: true
Layout.fillHeight: true
StackLayout {
id: stackLayout
anchors.fill: parent
function advance() { currentIndex = (currentIndex + 1) % count }
Repeater {
id: stackRepeater
model: 5
Rectangle {
color: Qt.hsla((0.5 + index)/stackRepeater.count, 0.3, 0.7, 1)
Button { anchors.centerIn: parent; text: "Page " + (index + 1); onClicked: { stackLayout.advance() } }
}
}
}
}
}
}
}

当我将代码放在一个文件中时,它可以工作,并且应用程序窗口不会小于子元素"mainLayout"的最小高度和宽度。但是拆分为 2 个文件不起作用。.

您无法将QML 元素的属性minimumWidth与 idmainLayout一起使用的原因是它没有serial.mainLayout.minimumWidth

但是,有问题的 QML 元素确实具有附加属性Layout.minimumWidth因为它是 ColumnLayout 中的一个项目,IDwrapper。您已经发现可以通过serial.mainLayout.Layout.minimumWidth.

启用 minimumWidth formainLayout的附加属性机制并不是最容易理解的。简而言之,它使对象能够使用额外的属性进行批注,这些属性在其他情况下对对象不可用,但在某些情况下是相关的。在这种情况下,minimumWidth 被认为与 ColumnLayout 的子项相关。列布局中的项支持这些附加属性。

最新更新