2014-02-26 65 views
3

我有一個自定義QML元素,我在我的應用程序中使用。如何從C++中的文件創建自定義QML元素?

MyImageView.qml

我可以使用ComponentDefinition沒有問題JavaScript創建它的實例,如(大大簡化了可讀性的緣故名稱和方法):

attachedObjects: [ 
    ComponentDefinition { 
     id: defMyImageView 
     MyImageView { } 
    } 
] 

function addCustom() { 
    var obj = defMyImageView.createObject(); 
    obj.customSource = "xyz"; 
    myContainer.add(obj); 
} 

我該怎麼辦了在保持當前MyImageView.qml文件的同時使用C++?

回答

1

想通了後多搜索和實驗)

void ArticleParser::addImage(QString imageUrl, QString title) { 
    QmlDocument *document = QmlDocument::create(
      "asset:///Articles/ArticleImage.qml"); //load qml file 
    document->setParent(rootContainer); 

    if (!document->hasErrors()) { 
     //Create Imageview 
     Control *control = document->createRootObject<Control>(); 
     control->setProperty("source", imageUrl); //custom property 
     control->setProperty("caption", title); //custom property 

     rootContainer->add(control); //add control to my main container 
    } 
} 

上述方法是從C++調用使用我的自定義圖像控制(支持的HTTP URL)增加圖象,因此它可以動態地加入。

相關問題