由于QVariant在qml中构建解析大量数据时,效率较低,比如有60万个点时,C++用QVariant传到qml中时,界面就会很卡。所以逆向思维,把qml界面对象指针传给c++,在c++中渲染界面数据。
下面讲具体实现:
1.c++创建对象并暴露给qml,并定义槽函数给qml直接调用
global.h:
class Global : public QObject
{
Q_OBJECT
public slots:
void updateChart(QObject *qmlView);
}
void Global::updateChart(QObject *qmlView)
{
if (qmlView) {
QVariant ret;
QMetaObject::invokeMethod(qmlView, "createSeriesAndReturnPointer", Q_RETURN_ARG(QVariant, ret), Q_ARG(QVariant, 1));
QLineSeries *series = qvariant_cast<QLineSeries *>(ret);
series->append(QPointF(1, 0.5));
series->append(QPointF(11, 0.5));
}
}
main.cpp:
engine.rootContext()->setContextProperty("Global", Global::instance());
2.qml 中实现动态创建界面元素的函数供c++调用,并调用c++槽函数更新界面: