2012-08-04 82 views
6

我在寫一個QML + Qt應用程序。 予定義的類是這樣的:如何將C++模型公開到QML

class MainClass : public QObject 
{ 
    Q_OBJECT 

public: 
    rosterItemModel m_rosterItemModel; 
. 
. 
. 
} 

rosterItemModel模型是從QAbstractListModel派生的類。 我暴露MainClass使用此功能QML部分:

qmlRegisterType<MainClass>("CPPIntegrate", 1, 0, "MainClass"); 

現在我想從分配這個MainClass模型(m_rosterItemModel)模型在QML一個ListView的財產。 我嘗試以下方法,但他們都不是有幫助:(

  • 我想聲明m_rosterItemModel作爲使用Q_PROPERTY的屬性。 我不能這樣做,因爲它說,QAbstractListModel不是 複製能力。
  • 我試着使用MainClass一個 Q_INVOKABLE函數來獲得一個指向m_rosterItemModel在QML文件,但它不是也有幫助。

有人能幫助我嗎?

回答

6

不應該有任何必要的元類型註冊。 所有你需要的就是調用setContextProperty和指針傳遞模型:

QQmlContext* context = view->rootContext(); //view is the QDeclarativeView 
context->setContextProperty("_rosterItemModel", &mainClassInstance->m_rosterItemModel); 

使用它在QML:

model: _rosterItemModel 

通過指針是很重要的,因爲QObject的的不是拷貝構造和無論如何,複製它們會破壞它們的語義(因爲它們具有「身份」)。

直接註冊模型的替代方法是註冊主類的實例並使用Q_INVOKABLE。在MainClass:

Q_INVOKABLE RosterItemModel* rosterItemModel() const; 

註冊mainClass的實例(mainClassInstance再次被假定爲一個指針):

context->setContextProperty("_mainInstance", mainClassInstance); 

在QML:

model: _mainInstance.rosterItemModel() 
+0

我使用qmlRegisterType在註冊MainClass到QML爲了在QML中輕鬆使用MainClass信號和插槽,可以通過創建MainClass {id:mc}這樣的實例來實現。無論如何。謝謝你:) – saeed 2012-08-04 07:05:56

+2

從經驗看來,在第二種情況下在necassary註冊了模型類:'qmlRegisterType (「CPPIntegrate」,1,0,「MainClass」);'另外,使用'const'修改器似乎打破了互操作。最後一個古怪的位是在頭的Q_PROPERTY和Q_INVOKABLE聲明中始終引用具有完整名稱空間限定的類。此外,如果有人試圖返回一些基類(如QAbstractItemModel)指針,互操作性將再次失敗,所以要小心。 – mlvljr 2012-08-05 15:07:44

+0

如何獲取mainClassInstance? – Brent81 2013-02-23 14:39:10