Reputation: 1514
When I try to access a son of a Tab element, if it is not active QML throws an error saying is undefined
.
main.qml
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.0
ApplicationWindow {
TabView {
Tab {
id: mytab1
}
Tab {
id: myTab2
Rectangle {
//(...)
}
}
}
Connections {
target: eventManager
onData: {
var scene = myTab2.children[0];
console.log(scene);
}
}
}
So, if myTab2 is active, I can see in the console QQuickItem_QML_15(0x27f1e2e0)
. If myTab2 is not active, then qml throws TypeError: Cannot read property 'children' of undefined
.
Why is undefined if the tab is not active and how can I fix it?
Thanks!
Upvotes: 2
Views: 549
Reputation: 49289
A TabView
doesn't create its content items until a tab is activated.
Your example begins at tab 1, at this point the rectangle in tab 2 doesn't exist, so you get undefined
. If you activate tab 2 the rectangle will be created, and then if you go back to tab 1 you will not get undefined
.
A Tab
inherits a Loader
, and comes with an active
property. I suppose there is an optimization that exists back in the Loader
component to delay loading until the element becomes visible. If you set active: true
in your Tab
it will be loaded before the tab is activated. Note that this will not make the tab view open with the second tab active.
Tab {
id: t2
active: true
Rectangle {
}
}
Upvotes: 2
Reputation: 1514
From the Qt documentation website, I've found a solution.
Tabs are lazily loaded; only tabs that have been made current (for example, by clicking on them) will have valid content. You can force loading of tabs by setting the active property to true:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.0
ApplicationWindow {
TabView {
Tab {
id: mytab1
active: true
}
Tab {
id: myTab2
active: true
Rectangle {
//(...)
}
}
}
Connections {
target: eventManager
onData: {
var scene = myTab2.children[0];
console.log(scene);
}
}
}
So, I've added the property active: true
in both tabs, and It works fine!
Upvotes: 3