1.基于基类QQuickPaintedItem,自定义UI显示类,内部实现属性以及对qml可见的函数方法,在使用前要先注册
//1.cpp class
class LabelPaper : public QQuickPaintedItem
{
Q_OBJECT
public:
Q_INVOKABLE void createText(QQuickItem* qmlParent, ....)
{
DataObj dataObj;
//....
addObject<ItemText*>("ItemText", dataObj/*自定义数据结构对象*/, qmlParent, ...);
}
}
//2. cpp call register before you use it
qmlRegisterType<LabelPaper>("UserControl", 1, 0, "LabelPaper");
2.在qml文件中使用,就像其它系统内置类型一样
import UserControl 1.0
Rectage {
id: mainView
LabelPaper{ id: paperView }
Button {
id: addItemBtn
onClicked:{ paperView.createText(paperView, x, y); }
}
}
3.使用在cpp代码中给其添加自己需要的内部UI组件, qml中调用了接口方法createText,内部再调用addObject,可以携带任何自己定义的业务数据。
// cpp add child item to paperView
QObject* createQmlObj(QQuickItem* qmlParent /*= paperView*/, const QString& qmlType = /*any type you defined*/)
{
QQmlEngine* engine = qmlEngine(qmlParent);
if (!engine)
return nullptr;
QQmlComponent component(engine);
component.setData( QString("import UserControl 1.0; %1 { }").arg(qmlType).toUtf8(), QUrl());
auto comObj = component.create();
comObj->setParentItem(qmlParent); //must set parent item !!!!
return comObj;
}
template<class T>
T* addObject(const QString& qmlType, DataObject* DataObject/*store your any data*/, QQuickItem* qmlParent)
{
auto qmlObject = createQmlObj(qmlParent, qmlType);
if (!qmlObject)
return nullptr;
// be attention, qmlType should have some connetion with T, such as qmlType is "ItemText", and "T" is ItemText
//
auto item = qobject_cast<T*>(qmlObject);
if (!item)
{
delete qmlObject;
return nullptr;
}
return item
}
4.QQmlComponent 在setData时,可以是之前注册过的自定义类型,也是是系统内置类型。
5.如果想在C++代码中使用封装的qml组件,需要使用qmlRegisterType进行注册,注意传入qml文件的QUrl
//1.cpp class
class BarCodeItem : public QQuickPaintedItem
{
}
//2. register qml define type
qmlRegisterType(QUrl("qrc:/ui/qml/label/BarCodeItem.qml"), "UserControl", 1, 0, "BarCodeItem");
//register cpp define type as a new uri
qmlRegisterType<LabelBarcode>("UserControl.Templates", 1, 0, "BarCodeItem");
//3. in BarCodeItem.qml
import UserControl.Templates 1.0 as T //import cpp object with new uri registered
T.BarCodeItem{ //cpp object define
id: barcodeItem
MouseArea{
}
}
//4. call
Q_INVOKABLE void createBarCode(QQuickItem* qmlParent, ....)
{
DataObj dataObj;
//....
//inner call "import UserControl 1.0; %1 { }", create object with BarCodeItem.qml file
addObject<BarCodeItem*>("BarCodeItem", dataObj/*自定义数据结构对象*/, qmlParent, ...);
}