(鼠标旋转功能)
#include <iostream> using namespace std; #include<gl/glut.h> GLfloat transx,transy; GLfloat scale; int primw=300; int primh=300; GLfloat rotatex=0,rotatey=0; GLint mousepx,mousepy; void rend(void) { glClear(GL_COLOR_BUFFER_BIT); glPointSize(8); glLineWidth(2); glColor3f(1,0,0); glPushMatrix(); glTranslatef(transx,transy,0); glRotatef(rotatex,1,0,0); glRotatef(rotatey,0,1,0); glBegin(GL_LINES); glVertex3f(0,0,0); glVertex3f(0,2,0); glVertex3f(0,0,0); glVertex3f(2,0,0); glVertex3f(0,0,0); glVertex3f(0,0,2); glEnd(); glBegin(GL_LINES); glVertex3f(0,0,0); glVertex3f(10,6,0); glVertex3f(10,10,0); glEnd(); glPopMatrix(); glFlush(); } void reshape(int w, int h) { glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(w<=h) gluOrtho2D(-10,10,-10.0/w*h,10.0/w*h); else gluOrtho2D(-10.0/h*w,10.0/h*w,-10,10); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if(w<=h) { /* scale=(GLfloat)primw/w;*/ transx=(50-w/2.0)*20.0/w; transy=(50-h/2.0)*20.0/w; } else { /* scale=(GLfloat)primh/h;*/ transx=(50-w/2.0)*20.0/h; transy=(50-h/2.0)*20.0/h; } } void motion(int x, int y) { int w,h; w=glutGet(GLUT_WINDOW_WIDTH); h=glutGet(GLUT_WINDOW_HEIGHT); if(0<=x && x<=w && 0<=y && y<=h) { rotatex=(mousepy-y)/(GLfloat)h*360; rotatey=(mousepx-x)/(GLfloat)w*360; /* cout<<"rotatex:rotatey"<<rotatex<<" "<<rotatey<<endl;*/ glutPostRedisplay(); } } void mousedown(int mouse, int state , int x, int y) { if(state== GLUT_DOWN) { mousepx=x; mousepy=y; } // cout<<"mousepx:mousepy"<<endl; // cout<<mousepx<<" "<<mousepy<<endl; } int main(int argc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(primw,primh); glutCreateWindow("coordination"); glClearColor(1,1,1,0); glutDisplayFunc(rend); glutMotionFunc(motion); glutMouseFunc(mousedown); glutReshapeFunc(reshape); glutMainLoop(); return 0; }
以上代码的使用:
1,、放在控制台应用程序中运行会出现控制台界面(黑框)
2、新建一个Qt工程Qt Application:
删除无用的文件(*.ui等),仅剩下main.cpp即可
将代码复制到main.cpp中运行,没有控制台出现。
工程下载地址(注意电脑要配置Qt):http://pan.baidu.com/s/1gdEeZgZ