QT与OpenGL之旋转
这篇文章是来讲述如何在OpenGL中选择图形的,我拿上次写的三角形来实现。
在OpenGL中有专门负责旋转的函数glRotatef(Angle, X Vector, Y Vector, Z Vector);此函数负责让对象绕着某个轴旋转。
Angle通常是某个变量代表对象转过的角度;
X Vector,Y Vector, Z Vector三个参数共同决定旋转轴的方向,(1, 0, 0)表示描述的矢量经过X轴的1个单位处并且方向向右;
当然你还得添加鼠标按钮的函数来实现逐步变化:
void GLWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) //按左键旋转
{
mousehandle();
}
}
void GLWidget::mousehandle()
{
rTri += 5;
if (rTri > 360)
{
rTri -= 360;
}
this->updateGL();
}
整个cpp文件如下:
#include "glwidget.h"
#include "ui_glwidget.h"
#include <QtGui>
#include <QtCore>
GLWidget::GLWidget(QGLWidget *parent) :
QGLWidget(parent),
ui(new Ui::GLWidget)
{
ui->setupUi(this);
rTri = 0.0;
fullscreen = false;
}
void GLWidget::getScreenInfo() //得到当前计算机的屏幕分辨率
{
QDesktopWidget* desktopWidget = QApplication::desktop();
QRect screenRect = desktopWidget->screenGeometry();
g_nActScreenW = screenRect.width();
g_nActScreenH = screenRect.height();
}
void GLWidget::initializeGL() //初始化
{
setGeometry(0, 0, g_nActScreenW, g_nActScreenH);//设置窗口初始位置和大小
glShadeModel(GL_FLAT);//设置阴影平滑模式
glClearColor(0.0, 0.0, 0.0, 0);//改变窗口的背景颜色
glClearDepth(1.0);//设置深度缓存
glEnable(GL_DEPTH_TEST);//允许深度测试
glDepthFunc(GL_LEQUAL);//设置深度测试类型
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);//进行透视校正
}
void GLWidget::paintGL()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
//renderText(10,20,"Hello,My Dear");
// glColor3f(1.0, 0.0, 0.0);
/*
glBegin(GL_TRIANGLES);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(-1.0, -1.0, 0.0);
glVertex3f(1.0, -1.0, 0.0);
glEnd();
*/
// glTranslatef(-1.5, 0.0, -6.0);
glRotatef(rTri, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glEnd();
glLoadIdentity();
renderText(20, 100, "Hello Jcy, My first OpenGL app.");
}
//该程序是设置opengl场景透视图,程序中至少被执行一次(程序启动时).
void GLWidget::resizeGL(int width, int height)
{
if(0 == height)
height = 1;//防止一条边为0
glViewport(0, 0, (GLint)width, (GLint)height);//重置当前视口,本身不是重置窗口的,只不过是这里被Qt给封装好了
glMatrixMode(GL_PROJECTION);//选择投影矩阵
glLoadIdentity();//重置选择好的投影矩阵
// gluPerspective(45.0, (GLfloat)width/(GLfloat)height, 0.1, 100.0);//建立透视投影矩阵
// glMatirxMode(GL_MODELVIEW);//以下2句和上面出现的解释一样
glLoadIdentity();
}
void GLWidget::keyPressEvent(QKeyEvent *e)
{
switch(e->key())
{
//F1键为全屏和普通屏显示切换键
case Qt::Key_F1:
fullscreen = !fullscreen;
if(fullscreen)
showFullScreen();
else
{
setGeometry(0, 0, g_nActScreenW, g_nActScreenH);
showNormal();
}
updateGL();
break;
//Ese为退出程序键
case Qt::Key_Escape:
close();
}
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) //按左键旋转
{
mousehandle();
}
}
void GLWidget::mousehandle()
{
rTri += 5;
if (rTri > 360)
{
rTri -= 360;
}
this->updateGL();
}
GLWidget::~GLWidget()
{
delete ui;
}