qt opengl lesson2 繪製一個三角形和一個正方形
阿新 • • 發佈:2019-01-28
在lesson1的基礎上加入一個三角形和一個正方形。
#------------------------------------------------- # # Project created by QtCreator 2017-01-19T20:33:38 # #------------------------------------------------- QT += core gui opengl greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = lesson2 TEMPLATE = app SOURCES += main.cpp \ myglwidget.cpp HEADERS += \ myglwidget.h LIBS += -lglut -lGLU
#ifndef MYGLWIDGET_H #define MYGLWIDGET_H #include <QGLWidget> #include <QKeyEvent> class MyGLWidget : public QGLWidget { Q_OBJECT public: explicit MyGLWidget(QWidget *parent = 0); ~MyGLWidget(); protected: virtual void paintGL(); virtual void initializeGL(); virtual void resizeGL(int w, int h); virtual void keyPressEvent(QKeyEvent *event); private: bool mFullScreen; }; #endif // MYGLWIDGET_H
#include <QApplication> #include <GL/glu.h> #include "myglwidget.h" MyGLWidget::MyGLWidget(QWidget *parent) { showNormal(); } MyGLWidget::~MyGLWidget() { } void MyGLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(-1.5f, 0.0f, -6.0f); // draw triangle glBegin(GL_TRIANGLES); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f); glEnd(); glTranslatef(3.0f, 0.0f, 0.0f); glBegin(GL_QUADS); glVertex3f(-1.0f, 1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glEnd(); } void MyGLWidget::initializeGL() { glShadeModel(GL_SMOOTH); glClearColor(0.0f, 0.0f, 1.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void MyGLWidget::resizeGL(int width, int height) { if (height == 0) height = 1; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void MyGLWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_F2: { mFullScreen = !mFullScreen; if (mFullScreen) showFullScreen(); else showNormal(); updateGL(); break; } case Qt::Key_Escape: { qApp->exit(); break; } } }
#include <QApplication>
#include "myglwidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyGLWidget w;
w.show();
return a.exec();
}