Добавление TabButton динамически в TabBar в QML

Я пытаюсь добавить tabButton в TabBar динамически при нажатии кнопки, но я потратил много времени на поиск, но не понимаю, как добавить, ниже приведен код, над которым я работаю:

MyTabButton.qml

import QtQuick 2.4
import QtQuick.Controls 2.2

Item
{
    property int BtnWidth:0
    property int BtnHeight:0
    property string BtnText: ""
    property bool isChecked : false

    TabButton
    {
        id:tabBtn
        text:BtnText
        width:BtnWidth
        height:BtnHeight

    }
}

MainForm.qml

import QtQuick 2.4
import QtQuick.Controls 2.2

Rectangle
{
    Button
    {
        id:button
        width:100
        height:100
        anchors.top:parent.top
        text:qStr("Add")
        onClicked{
            //How to add logic here to add tab in below tabBar.
        }
    }
    TabBar
    {
        id:tabBar
        anchors.top:button.bottom
        width:500
        height:500
    }
}

4 ответа

Решение

Вам нужно иметь что-то вроде Component это TabButton, Ваш файл MyTabButton.qml не приведет к TabButton, но вместо Item содержащий TabButtonно с этим ваш TabBar не знает что делать.

Таким образом, ваш файл должен иметь TabButton как корневой элемент

//MyTabButton.qml

import QtQuick 2.4
import QtQuick.Controls 2.2
TabButton
{
    id: tabBtn
    // customize as you like
}

Затем вы создаете этот компонент в своем файле, где вы хотите его использовать. (например, main.qml)

import QtQuick 2.4
import QtQuick.Controls 2.0

ApplicationWindow {
    width: 800
    height: 600
    visible: true

    TabBar {
        id: tabBar
        width: 800
        height: 50
    }

    // The component is like a factory for MyTabButtons now.
    // Use myTabButton.createObject(parent, jsobject-with-property-assignments) to create instances.
    Component {
        id: myTabButton
        MyTabButton {
            /// EDIT ACCORDING TO YOUR COMMENTS ***
            Connections {
                target: tabBar
                onCurrentIndexChanged: doSomething()
            }
            /// EDIT OVER
        }
    }

    Button {
        anchors.centerIn: parent
        // Create a object out of the component, and add it to the container
        onClicked: tabBar.addItem(myTabButton.createObject(tabBar /*, { object to set properties }*/))
    }
}

Пример:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: window
    width: 360
    height: 630
    visible: true

    header: TabBar {
        id: tabBar
    }

    Component {
        id: tabButton
        TabButton { }
    }

    Button {
        text: "Add"
        anchors.centerIn: parent
        onClicked: {
            var tab = tabButton.createObject(tabBar, {text: "Tab " + tabBar.count})
            tabBar.addItem(tab)
        }
    }
}

TabBar наследуется Container, у которого есть addItem(),

Попробуйте в Window

      Row {
    anchors.fill: parent
    TabBar {
        id: tabBar

        currentIndex: 0
        width: parent.width - addButton.width

        TabButton { text: "TabButton" }
    }

    Component {
        id: tabButton
        TabButton { text: "TabButton" }
    }

    Button {
        id: addButton
        text: "+"
        flat: true
        onClicked: {
            tabBar.addItem(tabButton.createObject(tabBar))
            console.log("added:", tabBar.itemAt(tabBar.count - 1))
        }
    }
}
Другие вопросы по тегам