程序运行截图如下:
这里的主要框架为Q3DScatter
首先是设置范围,免得随机生成坐标时,坐标系不停的变:
使用QScatter3DSeries生成一串的item。方便显示在m_graph中
使用QScatterDataItem进行元素的操作。
逻辑很简单把
旋转
关键代码
1 #include "widget.h"
2 #include "ui_widget.h"
3 #include <QtDataVisualization/QScatter3DSeries>
4 #include <QDebug>
5 #include <QThread>
6 #include <QTime>
7 #include <QTimer>
8 #include <QMessageBox>
9
10
11 Widget::Widget(QWidget *parent) :
12 QWidget(parent),
13 ui(new Ui::Widget)
14 {
15 ui->setupUi(this);
16 this->setWindowTitle("CSDN IT1995");
17 m_graph = new Q3DScatter();
18 m_graph->axisX()->setRange(-10, 10);
19 m_graph->axisY()->setRange(-10, 10);
20 m_graph->axisZ()->setRange(-10, 10);
21 QWidget *container = QWidget::createWindowContainer(m_graph);
22
23 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
24
25 if (!m_graph->hasContext()) {
26
27 QMessageBox msgBox;
28 msgBox.setText("Couldn‘t initialize the OpenGL context.");
29 msgBox.exec();
30 return;
31 }
32
33
34
35 //添加数据
36 QScatter3DSeries *item = new QScatter3DSeries();
37 item->setMesh(QAbstract3DSeries::MeshUserDefined);
38 item->setUserDefinedMesh(":/img/1cube.obj");
39
40 m_graph->addSeries(item);
41
42
43 //设置到控件上
44 QHBoxLayout *hLayout = new QHBoxLayout();
45 hLayout->addWidget(container, 1);
46 ui->widget->setLayout(hLayout);
47
48 //生成线,数据:
49 QScatterDataArray *dataArray = new QScatterDataArray;
50 dataArray->resize(5);
51 QScatterDataItem *ptrToDataArray = &dataArray->first();
52
53 for(int i = 0; i <= dataArray->size(); i++){
54
55 ptrToDataArray->setPosition(QVector3D(0, i, 0));
56 ptrToDataArray++;
57 }
58
59 item->dataProxy()->resetArray(dataArray);
60
61 //让其随机移动
62 m_timer = new QTimer(this);
63 connect(m_timer, &QTimer::timeout, [=](){
64
65 QScatterDataItem *ptr = &dataArray->first();
66
67 for(int i = 0; i < dataArray->size(); i++){
68
69 ptr->setPosition(QVector3D(qrand()%8 > 4 ? qrand()%8 : -qrand()%8,
70 qrand()%8 > 4 ? qrand()%8 : -qrand()%8,
71 qrand()%8 > 4 ? qrand()%8 : -qrand()%8));
72 ptr++;
73 }
74 item->dataProxy()->resetArray(dataArray);
75 });
76 m_timer->start(2000);
77
78 //让其自身旋转
79 m_rotationTimer = new QTimer(this);
80 connect(m_rotationTimer, &QTimer::timeout, [=]() mutable{
81
82 QScatterDataItem *ptr = &dataArray->first();
83
84 for(int i = 0; i < dataArray->size(); i++){
85
86 QQuaternion ruaternion = QQuaternion::fromAxisAndAngle(QVector3D(0.0f, 0.0f, 1.0f),
87 qrand()%600);
88 ptr->setRotation(ruaternion);
89 ptr++;
90 }
91 item->dataProxy()->resetArray(dataArray);
92 });
93 m_rotationTimer->start(100);
94 }
95
96 Widget::~Widget()
97 {
98 qDebug() << "Widget::~Widget()";
99 delete m_graph;
100 delete ui;
101 }