qml中重载QQuickPaintedItem实现自定义UI组件,并使用C++代码添加子UI对象

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, ...);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值