I have a problem when creating/destroying children of a TabBar dynamically.
This are the steps I'm making:
- Click on "Add tabs" -> tabs are created correctly
- Click on "Remove tabs" -> tabs are removed correctly
- Click on "Add tabs" -> tabs are not created anymore
This is my main.qml code:
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
width: 300
height: 200
visible: true
TabBar {
id: tabBar
anchors.fill: parent
function addTabButton(filename) {
Qt.createQmlObject(
'import QtQuick.Controls 2.15; TabButton { text: "' filename '" }',
tabBar)
}
}
Row {
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
Button {
text: "Add tabs"
onClicked: { tabBar.addTabButton("Tab 1"); tabBar.addTabButton("Tab 2") }
}
Button {
text: "Remove tabs"
onClicked: {
for (var i = 0; i < tabBar.children.length; i ) {
tabBar.children[i].destroy()
}
}
}
}
}
CodePudding user response:
When thinking about dynamic creation and destruction of components, the first consideration should be whether can you use model/delegate, e.g. ListModel
/Repeater
. This can (1) reduce code complexity, (2) increase code stability, and (3) and easier to read and maintain.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
TabBar {
width: parent.width
Repeater {
model: ListModel { id: listModel }
TabButton { text: filename }
}
}
footer: Frame {
RowLayout {
width: parent.width
Button {
text: "Add tabs"
onClicked: {
listModel.append( { filename: "Tab 1" } );
listModel.append( { filename: "Tab 2" } );
}
}
Button {
text: "Remove Tabs"
onClicked: listModel.clear()
}
}
}
}
You can Try it Online!