我试图用OpenGL和Qt显示一个三角形,但只得到一个黑色的窗口。 我做错了什么?
glwidget.h:
#pragma once
#include <QGLWidget>
class GLWidget : public QGLWidget {
public:
GLWidget(QWidget *parent = 0);
~GLWidget();
QSize sizeHint() const { return QSize(400, 400); }
protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
};
glwidget.cpp:
#include "glwidget.h"
GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) {}
GLWidget::~GLWidget(){ }
void GLWidget::initializeGL() { }
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(-1.5f,0.0f,-6.0f);
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();
}
void GLWidget::resizeGL(int w, int h)
{
QGLWidget::resize(w,h);
}
main.cpp中:
#include <QApplication>
#include "glwidget.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
GLWidget glWidget;
glWidget.show();
return app.exec();
}
答案 0 :(得分:5)
您必须在paintGL成员函数的开头设置视口和投影。把它放在paintGL的开头:
QSize viewport_size = size();
glViewport(0, 0, viewport_size.width(), viewport_size.height());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1, 1, -1, 1, 5, 7); // near and far match your triangle Z distance
glMatrixMode(GL_MODELVIEW);
此外,如果窗口是双缓冲的,则必须在绘制后交换缓冲区。设置
setAutoBufferSwap(true);
在构造函数中,在paintGL返回后交换,或者添加
swapBuffers();
在paintGL的末尾。
答案 1 :(得分:-1)
三角形转换出形式
glTranslatef(-0.5f,0.0f, 0.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLES);
glVertex3f( 0.0f, 0.2f, 0.0f);
glVertex3f(-0.2f,-0.2f, 0.0f);
glVertex3f( 0.2f,-0.2f, 0.0f);
glEnd();