2016-12-30 38 views
2

我想通過主文件中的ID訪問我的QML元素,但它不起作用。在我的測試(案例)的環境我有2個文件:Qt:通過QML中的ID任意訪問元素

  1. main.qml,這是我想通過ID
  2. Accounts.qml訪問該文件,這是我的元素定義的文件

main.qml

import QtQuick 2.7 
import QtQuick.Controls 2.0 

Item { 

    Accounts { 
     id: accounts 
    } 
    Component.onCompleted: { 
     console.log(accounts); 
     console.log(accounts.accounts_pane); 
     console.log(accounts.list_area); 
     console.log(accounts.accounts_pane.list_area.list_column.list_identities.model); 
    } 
} 

Accounts.qml

import QtQuick 2.7 
import QtQuick.Controls 2.0 

Pane { 
    id: accounts_pane 
    anchors { 
     fill: parent 
    }  
    Rectangle { 
     id: list_area 
     border.color: "black" 
     border.width: 2 
     anchors { 
      left: parent.left 
      right: parent.right 
      top: parent.top 
      bottom: parent.bottom 
     } 
     Column { 
      id: list_column 
      ListView { 
       id: list_identities 
       width: list_area.width 
       height: 200 
       model: ListModel { 
        ListElement { 
         name: "Bill Smith" 
         number: "555 3264" 
        } 
        ListElement { 
         name: "John Brown" 
         number: "555 8426" 
        } 
       } 
       delegate: Text { 
        text: name + ',' + number 
       } 
      } 
     } 
    } 
} 

因此,從main.qml文件我想更改帳戶的模型(不同的公司使用不同的帳戶),我需要用Javascript來完成。 (我的模型是一個C++類,在QML引擎中註冊,但我將使用Javascript來切換不同的模型對象)。符號訪問模式,按我的理解,應該是這樣的:

accounts.accounts_pane.list_area.list_column.list_identities.model 

然而,測試它的時候,用的console.log():

console.log(accounts); 
    console.log(accounts.accounts_pane); 
    console.log(accounts.list_area); 
    console.log(accounts.accounts_pane.list_area.list_column.list_identities.model); 

我無法通過通過Accounts.qml中定義的Pane {}元素。的qmlscene輸出顯示我這些錯誤:

hier $ qmlscene main.qml 
qml: QQuickPane(0x13b85f0) 
qml: undefined 
qml: undefined 
file:///QT_snippets/qmlscenes/hier/main.qml:13: TypeError: Cannot read property 'list_area' of undefined 

你怎麼能由ID從main.qml文件訪問QML元素隨意?

回答

1

您應該只使用id來訪問同一個QML文件中的對象。即使在一些時髦的情況下,似乎你可以通過ID訪問取決於QML文件的結構。它似乎可以從內部QML文件到外部。你的情況的反面。

如果要訪問其他QML文件中的元素,則必須將其顯示爲屬性。此外,只要命名相同的屬性將其遮蔽,就可以從整個項目中看到根QML文件中定義的屬性。

將QML文件中的每個對象看作是一個私有對象,而屬性是公共的。如果您想訪問其中一個私有對象,請將其作爲屬性公開。

property Item someItem : _item 
Item { id: _item } 

在你的情況accounts_pane是多餘的,因爲這將是一樣accounts - 這是同一個對象。

如果暴露list_identities直接就不需要暴露,以訪問所有以前的對象:此外

accounts.accounts_pane.list_area.list_column.list_identities.model // no need 
accounts.list_identities.model // all you need 

,可以公開特定對象的具體特性之別名:

// in Accounts.qml 
property alias mode: list_identities.model 
// then you can simply 
accounts.model 

最後,考慮這種方法是錯誤的,你不應該暴露外部使用的一切,你應該定義一個接口來控制每個QML組件的內部。

+0

非常感謝!關於界面,你如何定義界面?它是一個JavaScript函數嗎? – Nulik

+0

@Nulik - 它是一個屬性,函數或別名的集合 - 無論你需要什麼。例如,如果您只需要能夠設置模型,則將其作爲別名公開。 – dtech