我想在ChartView QML-Object中创建自己的特定图表。我的期望是通过在c ++中指定例如QCategoryAxis而不是在qml中调用此函数来获得充分的灵活性。
首先,我不太确定是否有可能像我希望的那样...... 而对于我非常简单的例子,我得到了一些我无法解决的错误。
如果有人可以帮助我,我会很高兴,因为两周以来我一直在努力使用这个QML / C ++组合。
diabchart.h
#ifndef DIABCHART_H
#define DIABCHART_H
#include <QtCharts/QChartView>
#include <QtCharts/QCategoryAxis>
#include <QObject>
QT_CHARTS_USE_NAMESPACE
class DiabChart : public QObject
{
Q_OBJECT
public:
explicit DiabChart(QObject *parent = 0);
public slots:
Q_INVOKABLE QCategoryAxis* getCategoryAxisY();
};
diabchart.cpp
#include "diabchart.h"
#include <QtCharts/QChartView>
QT_CHARTS_USE_NAMESPACE
DiabChart::DiabChart(QObject *parent)
: QObject(parent)
{
}
QCategoryAxis* DiabChart::getCategoryAxisY()
{
// Y-Axis (Bloodsugar)
QCategoryAxis *axisY = new QCategoryAxis();
axisY->append("critical", 50);
axisY->append("low", 70);
axisY->append("normal", 160);
axisY->append("high", 250);
axisY->append("extremly high", 450);
axisY->setRange(0, 450);
return axisY;
}
#endif // DIABCHART_H
的main.cpp
#include <QQmlApplicationEngine>
#include <QtCharts/QChartView>
#include <QApplication>
#include "diabchart.h"
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<DiabChart>("DiabChart", 1, 0, "DiabChart");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 1.4
import QtCharts 2.0
import DiabChart 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
DiabChart{
id: xyz
}
ChartView{
title: "Line"
anchors.fill: parent
antialiasing: true
//axes: xyz.getCategoryAxisY()
//Leads to: Error: Unknown method return type: QCategoryAxis*
//axes: getCategoryAxisY()
//Leads to: ReferenceError: getCategoryAxisY is not defined
//axes: DiabChart.getCategoryAxisY()
//Leads to: TypeError: Property 'getCategoryAxisY' of object [object Object] is not a function
ValueAxis{
id: vlaueAxisX
min: 0
max: 24
tickCount: 12
labelFormat: "%2.0f:00"
}
LineSeries {
axisX: vlaueAxisX
axisY: yAxis
name: "LineSeries"
XYPoint { id: zero; x: 0; y: 192.6}
XYPoint { id: first; x: 7; y: 89 }
XYPoint { x: 9; y: 100 }
XYPoint { x: 12; y: 50 }
XYPoint { x: 14; y: 250 }
XYPoint { x: 18; y: 140 }
XYPoint { x: 21; y: 80 }
XYPoint { id: last; x: 23.5; y: 200 }
XYPoint { id: twentyfour; x: 24; y: 192.6}
}
}
}
答案 0 :(得分:1)
所以,答案是返回QAbstractAxis*
。
为了能够在QML中使用C ++类型,源代码中的某处应该至少有Q_DECLARE_METATYPE()
个类型。由于Qt本身以AbstractAxis
QML类型运行(从图表API的qt文档中可以看出),因此已经为QAbstractAxis*
完成了。但是QCategoryAxis*
可能没有注册。