我已经创建了以下MWE (Qt 5.13.0):
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
property int itemsNo: 3;
id: window
visible: true
width: 480
height: 480
SwipeView
{
anchors.fill: parent;
id: theSwipeView;
Loader
{
sourceComponent: theSingleComp;
Component
{
id: theSingleComp;
Page
{
Text
{
text: "The single one";
}
}
}
}
Repeater
{
model: itemsNo;
Loader
{
sourceComponent: theMultiComp;
Component
{
id: theMultiComp;
Page
{
Text
{
text: "The multi one " +
(theSwipeView.currentIndex - 1);
}
}
}
}
}
}
}在我的程序中,我有一个独特的组件(theSingleComp)和多个组件(theMultiComp)。目前,我需要实现以下功能:
如果用于theMultiComp的模型只有1个项目,则仅显示此项目,而不显示theSingleComp。如果有更多的theMultiComp项,请像现在这样显示它。在我看来,如果我保持静态定义的项,这是不可能的。但另一方面,我不知道如何动态地执行此操作,因为在某些情况下,其中一个组件根本不应该显示。我尝试过这样的方法:
sourceComponent: (itemsNo > 1) ? theSingleComp : null;但是仍然会创建这个空组件的页面。
发布于 2019-09-05 21:59:28
您的问题是,Loader是一个Item,即使它没有源组件,SwipeView也会为它创建一个页面。
要解决此问题,您可以使用模型为1的Repeater (或将其禁用为0)。Repeater也是一个Item,但是它有一些特殊的代码可以被容器忽略。
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
id: window
property int itemsNo: 0
visible: true
width: 480
height: 480
SwipeView {
id: theSwipeView
anchors.fill: parent
Repeater {
model: window.itemsNo > 1 ? 1 : 0
Page {
Text {
text: "The single one"
}
}
}
Repeater {
model: window.itemsNo
Page {
Text {
text: "The multi one " + model.index
}
}
}
}
}(我已经简化了代码,删除了显式组件和加载器)
发布于 2019-09-05 19:16:17
我提出了以下解决方案,但我对它并不满意。它非常复杂,用户可以看到页面索引是如何变化的。
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
property int itemsNo: 2;
id: window
visible: true
width: 480
height: 480
SwipeView
{
anchors.fill: parent;
id: theSwipeView;
Component.onCompleted:
{
if (itemsNo > 1)
insertItem(0, theSingleComp);
set0IndexTimer.start();
}
Timer
{
id: set0IndexTimer;
interval: 1;
running: false;
repeat: false;
onTriggered: theSwipeView.setCurrentIndex(0);
}
onCurrentIndexChanged: console.log("page: ", currentIndex);
Repeater
{
model: itemsNo;
Loader
{
sourceComponent: theMultiComp;
Component
{
id: theMultiComp;
Page
{
Text
{
text: "The multi one " + theSwipeView.currentIndex;
}
}
}
}
}
}
Item
{
id: theSingleComp;
Page
{
Text
{
text: "The single one";
}
}
}
}我还在寻找一些其他的例子。
https://stackoverflow.com/questions/57803996
复制相似问题