2014-03-06 86 views
2

我是Qt Quck和Qt5/PyQt的新手,現在我遇到了一個奇怪的問題。我想在下面的QML定義這樣來找到對象名「試驗」的對象:QObject :: findChild()返回None沒有明顯的原因

self.rootObject().findChild(QObject, "test") 

但調用返回無。但是,如果我將objectName: "test"屬性移動到父級Tab元素,則會成功找到它。這只是在孩子Item內部找不到。同樣,addChannel,modifyChannelremoveChannel物體也未被findChild()找到。

import QtQuick 2.0 
import QtQuick.Layouts 1.1 
import QtQuick.Controls 1.1 
import "TouchStyles" 

Item { 
    ListModel { } 

    TouchButtonFlatStyle { id: touchButtonFlat } 
    TouchTabViewStyle { id: touchTabView } 

    Rectangle { 
     width: 480 
     height: 230 

     TabView { 
      currentIndex: 0 
      tabPosition: 1 
      anchors.fill: parent 
      style: touchTabView 

      Tab { 
       title: "Play" 

       Item { 
        anchors.fill: parent 
        PianoKeyboard { anchors.centerIn: parent } 
       } 
      } 
      Tab { 
       title: "Channels" 
       Item { 
        objectName: "test" 
        ListView { 
         anchors.fill: parent 
         model: listModel 
         delegate: Channel {} 
        } 
        BorderImage { 
         border.bottom: 8 
         anchors.bottom: parent.bottom 
         source: "images/toolbar.png" 
         width: parent.width 
         height: 50 

         RowLayout { 
          anchors.verticalCenter: parent.verticalCenter 
          anchors.horizontalCenter: parent.horizontalCenter 

          Button { text: "Add"; objectName: "addChannel" } 
          Button { text: "Modify"; objectName: "modifyChannel" } 
          Button { text: "Remove"; objectName: "removeChannel" } 
         } 
        } 
       } 
      } 
     } 
    } 
} 

我在做什麼錯? Qt文檔說,搜索是遞歸執行的。爲什麼它不遍歷整個對象樹?

+0

最好的辦法是首先檢查搜索是否成功從C++。如果沒有,請將其報告爲Qt錯誤。否則,它會是一個PyQt錯誤。 –

+0

'self.rootObject()。findChildren(QObject)'(即所有孩子)的結果是什麼? –

+0

第一個標籤是否會發生同樣的情況(如果您將第二個標籤的Item複製到第一個標籤)?或者,如果您在執行findChild之前選擇第二個選項卡,那麼同樣的問題呢? – Schollii

回答

3

問題與標籤僅在需求時「實例化」有關。第一個標籤總是被實例化,所以如果你把objectName放在那裏,它會被發現。

僅當您實例化第二個選項卡(選中它)時,纔會在第二個選項卡中找到它。同樣,在TabView上使用findChild可能會實例化每個選項卡(因爲它正在查找它們),因此在此之後即使未選擇第二個選項卡,findChild也可以工作。

結論:首先實例的所有選項卡(做對TabView一個findChild是一種方式,但可能是黑客攻擊),然後爲項目做findChild

+0

我在根元素上執行'findChild'來查找TabView(找到),然後在TabView上執行'findChild'來查找Tab(找到),然後在Tab上執行findChild找到Button(找不到) 。如果我在臺式電腦上運行它(以前我在嵌入式ARM板上測試過),則會重現該問題。所以,Tab沒有被'findChild'實例化。另外,我查看了TabView的源代碼,除了TabView的樣式外,我沒有在其中找到任何延遲加載邏輯。在找到的Tab上運行findChildren(QObject)會返回兩個子對象:一個QObject和一個QQmllComponent。 – madprogrammer

+1

通過連接到'TabView'的onCurrentIndexChanged事件來解決。一旦事件被觸發,獲得活動的「Tab」的'currentIndex',然後根據調用函數的索引連接(現在實例化的)'Tab'子元素的信號。 – madprogrammer

相關問題