Динамическое добавление 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
    }
}

person pra7    schedule 27.07.2017    source источник


Ответы (3)


У вас должно быть что-то вроде 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 }*/))
    }
}
person derM    schedule 27.07.2017
comment
Это именно то, что мне нужно. Но если я хочу использовать функцию, созданную в MyTabButton, скажите doSomething(), как получить к ней доступ в tabBar Обработчик события onCurrentIndexChanged()? - person pra7; 27.07.2017
comment
Вы хотите вызывать doSomething для всех TabButtons или только для того, который стал активным? - person derM; 27.07.2017
comment
Мне нужно позвонить doSomething из всех TabButtons, так как я рисую на TabButton... - person pra7; 27.07.2017
comment
Звучит странно, но ладно. Решение заключается в том, что вы не получаете доступ к функции из обработчика onCurrentIndexChanged, а создаете соединение внутри TabButton, нацеленное на TabBar. Смотрите мое редактирование в коде (отмечено комментариями) - person derM; 27.07.2017

Пример:

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)
        }
    }
}
person jpnurmi    schedule 27.07.2017
comment
Это именно то, что мне нужно. Но если я хочу использовать функцию, созданную в TabButton, скажите doSomething(), как получить к ней доступ в tabBar Обработчик события onCurrentIndexChanged()? - person pra7; 27.07.2017
comment
Взгляните на API Container. Он обеспечивает доступ к текущему элементу или любому другому элементу, если хотите. - person jpnurmi; 27.07.2017

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

person dtech    schedule 27.07.2017
comment
Спасибо, и я уже упоминал об этом, но я хочу добавить новую вкладку на лету ... - person pra7; 27.07.2017