Undefined element when tab is not active

痴心易碎 提交于 2019-12-11 01:59:39

问题


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!


回答1:


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!




回答2:


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 {
    }
}


来源:https://stackoverflow.com/questions/29020087/undefined-element-when-tab-is-not-active

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!