这个实例展示了在图中添加自定义item。并且演示了如何去移动。
Obj网格文件添加到资源文件中。
注意:一般是在meshes上增加纹理,这里可以直接用QImage添加一个单独的颜色。
QImage color = QImage(2, 2, QImage::Format_RGB32);
color.fill(Qt::red);
通过QVector3D这个变量去设置这个位置
QVector3D positionOne = QVector3D(39.0f, 77.0f, 19.2f);
通过QCustom3DItem创建网格。
QCustom3DItem *item = new QCustom3DItem(":/items/oilrig.obj", positionOne,
QVector3D(0.025f, 0.025f, 0.025f),
QQuaternion::fromAxisAndAngle(0.0f, 1.0f, 0.0f, 45.0f),
color);
在graph中添加这个item
m_graph->addCustomItem(item);
使用removeCustomItemAt()移除某个位置的item
m_graph->removeCustomItemAt(positionOne);
这里要注意:移除了会会自动调用delete,如果不想释放想让其保留,可以使用releaseCustomItem()
下面对程序进行部分解析:
这里在pri文件中可以看到,使用了Qml和quick。
而在我们自己写的代码中没有使用到Qml和quick。如果去掉,程序不会发现编译问题,但运行会有问题。个人觉得是Qt里面3D相关的,使用了qml。会调用GPU来构建画面。
Q3DSurface:提供渲染3D平面图的方法。
下面是如果构造一个小型Q3DSurface图:
第一步把graph设置为最顶层window图
Q3DSurface surface;
surface.setFlags(surface.flags() ^ Qt::FramelessWindowHint);
这样就可以接收数据并渲染了,下面是创建几个item
QSurfaceDataArray *data = new QSurfaceDataArray;
QSurfaceDataRow *dataRow1 = new QSurfaceDataRow;
QSurfaceDataRow *dataRow2 = new QSurfaceDataRow;
填充数据:
*dataRow1 << QVector3D(0.0f, 0.1f, 0.5f) << QVector3D(1.0f, 0.5f, 0.5f);
*dataRow2 << QVector3D(0.0f, 1.8f, 1.0f) << QVector3D(1.0f, 1.2f, 1.0f);
*data << dataRow1 << dataRow2;
创建一个连续的集合存放data数据
QSurface3DSeries *series = new QSurface3DSeries;
series->dataProxy()->resetArray(data);
surface.addSeries(series);
最后是展示:
surface.show();
完整代码如下:
#include <QtDataVisualization>
using namespace QtDataVisualization;
int main(int argc, char **argv)
{
QGuiApplication app(argc, argv);
Q3DSurface surface;
surface.setFlags(surface.flags() ^ Qt::FramelessWindowHint);
QSurfaceDataArray *data = new QSurfaceDataArray;
QSurfaceDataRow *dataRow1 = new QSurfaceDataRow;
QSurfaceDataRow *dataRow2 = new QSurfaceDataRow;
*dataRow1 << QVector3D(0.0f, 0.1f, 0.5f) << QVector3D(1.0f, 0.5f, 0.5f);
*dataRow2 << QVector3D(0.0f, 1.8f, 1.0f) << QVector3D(1.0f, 1.2f, 1.0f);
*data << dataRow1 << dataRow2;
QSurface3DSeries *series = new QSurface3DSeries;
series->dataProxy()->resetArray(data);
surface.addSeries(series);
surface.show();
return app.exec();
}