ChartView 不是 QChartView 而是 QQuickItem 所以投射不起作用。
所以你不能直接访问方法,而是使用 QMetaObject ,如下所示:
助手.h
#ifndef HELPER_H
#define HELPER_H
#include <QObject>
class QQuickItem;
class Helper : public QObject
{
Q_OBJECT
public:
using QObject::QObject;
Q_INVOKABLE void createSerie(QQuickItem *chartview);
Q_INVOKABLE void removeAllSeries(QQuickItem *chartview);
};
#endif // HELPER_H
助手.cpp
#include "helper.h"
#include <QAbstractAxis>
#include <QAbstractSeries>
#include <QLineSeries>
#include <QMetaObject>
#include <QQuickItem>
#include <random>
#include <cstring>
QT_CHARTS_USE_NAMESPACE
void Helper::createSerie(QQuickItem *chartview){
if(!chartview)
return;
const QMetaObject *mo = chartview->metaObject();
if(std::strcmp(mo->className(), "QtCharts::DeclarativeChart") != 0)
return;
int ix = mo->indexOfEnumerator("SeriesType");
QMetaEnum me = mo->enumerator(ix);
int type = me.keyToValue("SeriesTypeLine");
QAbstractAxis *axis_x = nullptr;
QMetaObject::invokeMethod(chartview, "axisX", Qt::DirectConnection,
Q_RETURN_ARG(QAbstractAxis *, axis_x));
QAbstractAxis *axis_y = nullptr;
QMetaObject::invokeMethod(chartview, "axisY", Qt::DirectConnection,
Q_RETURN_ARG(QAbstractAxis *, axis_y));
QAbstractSeries *serie = nullptr;
QMetaObject::invokeMethod(chartview, "createSeries", Qt::DirectConnection,
Q_RETURN_ARG(QAbstractSeries *, serie),
Q_ARG(int, type),
Q_ARG(QString, "serie from c++"),
Q_ARG(QAbstractAxis *, axis_x),
Q_ARG(QAbstractAxis *, axis_y));
if(QLineSeries *line_serie = qobject_cast<QLineSeries *>(serie)){
static std::default_random_engine e;
static std::uniform_real_distribution<> dis(0, 3);
for(int i=0; i < 14; i++){
line_serie->append(i, dis(e));
}
}
}
void Helper::removeAllSeries(QQuickItem *chartview){
if(!chartview)
return;
const QMetaObject *mo = chartview->metaObject();
if(std::strcmp(mo->className(), "QtCharts::DeclarativeChart") != 0)
return;
QMetaObject::invokeMethod(chartview, "removeAllSeries", Qt::DirectConnection);
}
main.qml
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Layouts 1.14
import QtQuick.Controls 2.4
import QtCharts 2.14
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ColumnLayout{
anchors.fill: parent
RowLayout{
Button{
text: "Create serie"
Layout.fillWidth: true
onClicked: helper.createSerie(chartview)
}
Button{
text: "Clear series"
Layout.fillWidth: true
onClicked: helper.removeAllSeries(chartview);
}
}
ChartView {
id: chartview
title: "Line"
antialiasing: true
Layout.fillWidth: true
Layout.fillHeight: true
LineSeries {
name: "LineSeries"
XYPoint { x: 0; y: 0 }
XYPoint { x: 3; y: 2.1 }
XYPoint { x: 8; y: 3.3 }
XYPoint { x: 10; y: 2.1 }
XYPoint { x: 11; y: 4.9 }
XYPoint { x: 12; y: 3.0 }
XYPoint { x: 13; y: 3.3 }
}
axes: [
ValueAxis{
id: xAxis
min: 1.0
max: 15.0
},
ValueAxis{
id: yAxis
min: 0.0
max: 5.0
}
]
}
}
}
下面的链接是完整的代码。