2015-11-19 72 views
-1

我將在ApplicationWindow中創建一個包含MenuBar組件的單獨文件。我有一個原始文件是這樣的:在ApplicationWindow中爲MenuBar創建一個單獨的QML文件

ApplicationWindow { 
    visible: true 
    width: 640 
    height: 480 
    title: qsTr("Hello World") 

    menuBar: MenuBar { 
     Menu { 
      title: qsTr("File") 
      MenuItem { 
       text: qsTr("&Open") 
       onTriggered: console.log("Open action triggered"); 
      } 
      MenuItem { 
       text: qsTr("Exit") 
       onTriggered: Qt.quit(); 
      } 
     } 
    } 

    Label { 
     text: qsTr("Hello World") 
     anchors.centerIn: parent 
    } 
} 

不過,我想分開都做出更復雜的菜單在這樣一個單獨的文件:

第一個文件:

ApplicationWindow { 
    visible: true 
    width: 640 
    height: 480 
    title: qsTr("Hello World") 

    menuBar: MyMenuBar{ 
    } 

    Label { 
     text: qsTr("Hello World") 
     anchors.centerIn: parent 
    } 
} 

第二個文件: (MyMenuBar.qml)

MenuBar { 
    Menu { 
     title: qsTr("File") 
     MenuItem { 
      text: qsTr("&Open") 
      onTriggered: console.log("Open action triggered"); 
     } 
     MenuItem { 
      text: qsTr("Exit") 
      onTriggered: Qt.quit(); 
     } 
    } 
} 

我試過這個解決方案,但是當我嘗試啓動程序時,它說MyMenuBar is not a type

怎麼了?

+1

您的項目是否使用'.qrc'文件?如果是這樣,請嘗試再次運行'qmake',方法是右鍵單擊Creator中的項目並按下'運行qmake',然後重新構建您的項目。 – Mitch

+0

@Mitch是對的。你的資源文件'.qrc'應該看起來像[this](https://gist.github.com/ftena/ef94e24d2e0727a26917)。 – Tarod

回答

0

您的qml文件沒有任何問題。如果您將這兩個文件放在同一個目錄中並運行qmlscene main.qml(考慮到main.qml是您的第一個文件),您將得到期望的結果。如果您在項目中使用C++代碼,則可能需要按照註釋中的建議在qrc文件中添加所有qml文件。如果你沒有這種願望,我認爲你的項目文件有問題。我建議您創建一個新的Qt Quick UI項目,並將您的第一個文件代碼放入創建的文件中,然後右鍵單擊該項目,然後單擊add new並選擇Qt > QML file並將其命名爲MyMenuBar.qml並將其放入其中。我認爲這應該可以解決你的問題。

相關問題