QML访问您的qml组件

时间:2016-04-08 12:04:34

标签: qt qml

我正在使用QML开发前端,我在从主QML窗口访问组件时遇到问题。所以,我的主要QML窗口是:

ApplicationWindow {
    id: rootWindow
    objectName: "window"

    property Component mainScreen: MainScreen {} // my component

    // This is a slot that gets called from C++ side.
    // The function gets called fine.
    function videoDone() {
        mainScreen.doVideo()
    }
}

MainScreen组件在MainScreen.qml文件中写为:

ControlView {
    id: mainScreenView
    objectName: "MainScreenView"


    function doVideo() {
        console.log("Called")
    }
}

但是,这不能按预期工作,我收到错误:

TypeError: Property 'doVideo' of object QQmlComponent is not a function

我认为问题在于,在ApplicationWindow级别没有看到MainScreen的完整定义。我试着看看我是否可以施展但是没有成功。

同样mainScreen.objectName返回空字符串而不是MainScreenView

5 个答案:

答案 0 :(得分:4)

我认为使用MainScreen组件的正确方法是这样做:

<强> main.qml

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    id: rootWindow
    objectName: "window"
    visible: true

    MainScreen { id: mainScreen } // my component

    Component.onCompleted: {
        mainScreen.doVideo()
    }
}

MainScreen.qml (代码与您相同,但我使用Item代替ControlView只是为了检查编译)

import QtQuick 2.5

Item {
    id: mainScreenView
    objectName: "MainScreenView"

    function doVideo() {
        console.log("Called")
    }
}

另一种选择是创建组件dynamically

答案 1 :(得分:2)

而不是

  

属性组件主屏幕:MainScreen {}

使用

  

Property var mainscreen:MainScreen {}

以下是示例代码

<强> main.qml

&#13;
&#13;
import QtQuick 2.6
import QtQuick.Controls 1.5

ApplicationWindow {
    id: rootWindow
    objectName: "window"
    visible: true

    property var mainScreen: MainScreen {  }

    Component.onCompleted: {
        mainScreen.doVideo()
    }
}
&#13;
&#13;
&#13;

<强> MainScreen.qml

&#13;
&#13;
import QtQuick 2.6

Item {
    id: mainScreenView
    objectName: "MainScreenView"

    function doVideo() {
        console.log("Called")
    }
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我猜你只想要这样的东西:

ApplicationWindow {
    // if you really need a property of your Item uncomment the following line:
    // property alias mainScreen : mainScreen

    MainScreen {
        id: mainScreen
    }
    function videoDone() {
        mainScreen.doSomething()
    }
}

并在MainScreen.qml中:

import QtQuick 2.0
Item {
    function doSomething()
    {
        console.debug("Test")
    }
}

答案 3 :(得分:0)

您应该为您的组件分配ID。

ApplicationWindow {

id: rootWindow
objectName: "window"

property Component mainScreen: MainScreen {
    id: myMainScreenCmp
 } // my component

function videoDone() {
    myMainScreenCmp.doVideo()
}

}

答案 4 :(得分:-1)

您必须导入组件,组件名称和文件名必须相同。

MainScreen.qml

MainScreen {
    id: mainScreenView
    objectName: "MainScreenView"

    function doVideo() {
        console.log("Called")
    }
}