Qml C++ 混合编程 Qml C++函数 相互调用

Qml 调用 c++ 函数

1 定义C++ 类 如 QMyModel 继承于 QObject

2 Qml 上下文 使实例变为gMyModel 属性 MyModel

QQmlContext *ctxt = ui.quickWidget->rootContext();
    ctxt->setContextProperty("MyModel", gMyModel);

3 定义C++类函数

 Q_INVOKABLE 将此宏应用于成员函数的声明,以允许通过元对象系统调用它们 


Q_INVOKABLE QVariantMap QMyModel::getCurrentInfo(int i)
{
	QList<QString> keysList =  elementMap.keys();
	if (keysList.isEmpty())
	{
		//return nullptr;
	}
	QString key = keysList[i];
	QMyElement element = elementMap[key];

	QVariantMap map;
	map.clear();

	map.insert("deviceID", element.deviceID);
	map.insert("donorID", element.donorID);
	map.insert("donorName", element.donorName);
	
	map.insert("ipAddress", element.ipAddress);
	map.insert("ipPort", element.ipPort);

	map.insert("protocol",  element.protocol);
	map.insert("drawPlasmaVolume", element.drawPlasmaVolume);
	map.insert("cycles", element.cycles);

	map.insert("drawPumpSpeed", element.drawPumpSpeed);
	map.insert("returnPumpSpeed", element.returnPumpSpeed);
	map.insert("cuffPressure", element.cuffPressure);
	map.insert("totalSalineVolume", element.totalSalineVolume);

	map.insert("dpmMaxPressure", element.dpmMaxPressure);
	map.insert("dpmMinPressure", element.dpmMinPressure);

	map.insert("bloodVolume", element.bloodVolume);
	map.insert("thePlasmaVolume", element.thePlasmaVolume);
	map.insert("theSalineVolume", element.theSalineVolume);
	

	return map;
}


 

4 调用 getCurrentInfo

function setCurrentItem()
    {
        var curInfo = MyModel.getCurrentInfo(gridView.currentIndex);

        deviceID = curInfo.deviceID
        donorID = curInfo.donorID
        donorName = curInfo.donorName

        ipAddress = curInfo.ipAddress
        ipPort = curInfo.ipPort

        protocol = curInfo.protocol
        drawPlasmaVolume = curInfo.drawPlasmaVolume
        cycles = curInfo.cycles

        drawPumpSpeed = curInfo.drawPumpSpeed
        returnPumpSpeed = curInfo.returnPumpSpeed
        cuffPressure = curInfo.cuffPressure
        totalSalineVolume = curInfo.totalSalineVolume

        dpmMaxPressure = curInfo.dpmMaxPressure
        dpmMinPressure = curInfo.dpmMinPressure

        bloodVolume = curInfo.bloodVolume
        thePlasmaVolume = curInfo.thePlasmaVolume
        theSalineVolume = curInfo.theSalineVolume

    }

 

 c++ 调用  Qml函数

1 首先获取 节点元素

QQuickItem *root = ui.quickWidget->rootObject();

2 调用 根节点元素方法

QMetaObject::invokeMethod(root, "changeColor");

3 获取其他元素

QObject *item = root->findChild<QObject*>("moban");

 Rectangle{
            objectName: "moban"
      }

注意这里用的是 objectName 而非 id

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章