【问题标题】:How to delete a stackLayout that was is associated with a tabButton in a TabBar如何删除与 TabBar 中的 tabButton 关联的 stackLayout
【发布时间】:2018-11-29 04:29:17
【问题描述】:

我创建了一个 Qt 空应用程序,其中 qml 代码如下。

我想要做的是单击“添加选项卡”按钮并创建选项卡和对应页面。但是,如果我删除(单击删除选项卡),它不会被完全删除! 如果我点击“添加 Tab2”按钮,它应该会出现在第二页。

如何解决?

main.qml:

import QtQuick 2.7
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.3
import QtQuick.Window 2.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button{
        id:createButton
        text:"add Tab"
        onClicked: { newTab(1) }
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

    Button{
        text:"remove Tab"
        onClicked: { closeTab() }
        anchors.right: createButton.left
        anchors.bottom: parent.bottom
    }

    Button{
        id:createButton2
        text:"add Tab2"
        onClicked: { newTab(2) }
        anchors.left: parent.left
        anchors.bottom: parent.bottom
    }

    function newTab (val) {
        var c = Qt.createComponent("Panel_"+val+".qml")
        var tab1 = c.createObject(content)
        tabBar.addItem(tabButton.createObject(tabBar, {text: "teste", "font.pixelSize": 14} ))
    }

    function closeTab(){
        var _contentData = tabBar.contentData
        for (var i = 0; i < _contentData.length; ++i)
        {
            if( _contentData[i]['contentItem']['text']==="teste"){
                    var _removeItem = tabBar.itemAt(i);
                    tabBar.removeItem(_removeItem);
            }
        }
        tabBar.setCurrentIndex(0)
    }


    header: TabBar {
        id: tabBar
        opacity:0.8
    }

    Component {
        id: tabButton
        TabButton {
            font.pixelSize: 14
        }
    }

    StackLayout {
        id: content
        currentIndex: tabBar.currentIndex
        anchors.fill: parent
    }


}

Panel_1.qml

import QtQuick 2.0

Item {
        property string title: qsTr("panel1")
    Text{text:"panel1"}    
}

Panel_2 qml 与 Panel_1 相同。

【问题讨论】:

  • 在 qml 中有一个叫做 TabView 的东西。这似乎是您当前设置的合适替代方案。你以前试过吗?

标签: qt qml


【解决方案1】:

你已经从 TabButton 中移除了对应的项目,但没有移除 StackLayout 对应的项目,所以你必须移除具有相同索引的子项,但是当你从列表中移除项目时,你必须从末尾迭代到开头.

function closeTab(){
    var _contentData = tabBar.contentData
    for (var i = _contentData.length -1 ; i >= 0; --i)
    {
        if( _contentData[i]['contentItem']['text']==="teste"){
            var _removeItem = tabBar.itemAt(i);
            tabBar.removeItem(_removeItem);
            content.children[i].destroy()
        }
    }
    tabBar.setCurrentIndex(0)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多