我使用QDeclarativeView
来显示QML小部件。我如何设置QDeclarativeView
/小部件的最小高度,所以它不会变得比我想要的小?我希望能够将它绑定到子部件的最小尺寸,这样部件就不会重叠,并且所有部件都保持适当的间距。
iBelevie的解决方案是可靠的,但有点过头了。QML在某种程度上是CSS的兴奋剂,并支持内联javascript。我希望你现在知道这是怎么回事了:)
简单地将属性定义为条件语句:height: (root.height < threshold) ? minHeight: WhateverIsEpressibleInJavaScript
。这不是一个灵活可靠的解决方案,但至少它是一个在标记内的单行。我把它留给读者去思考它是好是坏。
步骤#1:在QML中定义最小尺寸
首先,在您的主小部件中,创建两个属性来保存最小宽度和最小高度:property int minWidth: <whatever>
property int minHeight: <whatever>
如果您希望它基于小部件子元素的最小大小,您可以这样做:
Item {
id: root
property int minWidth: child.minWidth + 40; // Adds a 40px margin
property int minHeight: child.minHeight + 40; // Adds a 40px margin
Item {
id: child
property int minWidth: <whatever>
property int minHeight: <whatever>
anchors.centerIn: root
}
}
步骤#2:将QML中的最小大小连接到QDeclarativeView
的最小大小
然后,在创建QDeclarativeView
的类中,定义两个槽(view
是QDeclarativeView
):
void onMinimumWidthChanged() {
view->setMinimumWidth(view->rootObject()->property("minWidth").toInt());
}
void onMinimumHeightChanged() {
view->setMinimumHeight(view->rootObject()->property("minHeight").toInt());
}
然后,当您创建QDeclarativeView
:
QDeclarativeView *view = new QDeclarativeView(this);
view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
view->setSource(/* Whatever */);
QDeclarativeProperty(view->rootObject(), "minWidth").connectNotifySignal(this, SLOT(onMinimumWidthChanged()));
QDeclarativeProperty(view->rootObject(), "minHeight").connectNotifySignal(this, SLOT(onMinimumHeightChanged()));
onMinimumWidthChanged();
onMinimumHeightChanged();
现在,QDeclarativeView
的最小大小将绑定到主QML小部件中定义的最小大小。如果您在QML中更改了最小大小,那么QDeclarativeView
的最小大小也会更改。