gpt4 book ai didi

c++ - 在 QtCharts (ChartView) 的 c++Function 中定义 qml 对象

转载 作者:行者123 更新时间:2023-11-30 05:25:11 25 4
gpt4 key购买 nike

我想在 ChartView QML 对象中创建我自己的特定图表。我的期望是通过在 c++ 中指定例如 QCategoryAxis 而不是在 qml 中调用此函数来获得充分的灵 active 。

首先,我不太确定是否有可能像我希望的那样......对于我非常简单的示例,我遇到了一些我无法解决的错误。

如果有人能帮助我,我会很高兴,两周以来我一直在为这个 QML/C++ 组合而苦苦挣扎。

图表.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();

};

图表.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

主要.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();
}

主.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}
}
}
}

最佳答案

所以,答案是返回QAbstractAxis*

为了能够在 QML 中使用 C++ 类型,源代码中的某处至少应该有该类型的 Q_DECLARE_METATYPE()。由于 Qt 本身在 AbstractAxis QML 类型上运行(从图表 API 的 qt 文档中可以看出),那么这已经为 QAbstractAxis* 完成了。但是 QCategoryAxis* 可能没有注册。

关于c++ - 在 QtCharts (ChartView) 的 c++Function 中定义 qml 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com