用Qt和OpenGL显示一个三角形 [英] Displaying a triangle with Qt and OpenGL

查看:297
本文介绍了用Qt和OpenGL显示一个三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用OpenGL和Qt显示一个三角形,但只得到一个黑色窗口. 我在做什么错了?

I am trying to display a triangle with OpenGL and Qt but only get a black window. What am I doing wrong?

glwidget.h:

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:

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();
}

推荐答案

必须在paintGL成员函数的开头设置视口和投影.将其放在paintGL的开头:

You must set a viewport and projection at the beginning of the paintGL member function. Put this at the beginning of your 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);

此外,如果窗口是双缓冲的,则在绘制后必须交换缓冲区.要么设置

Also if the window is double buffered, the buffers must be swapped, after drawing. Either set

setAutoBufferSwap(true);

在构造函数中,在paintGL返回后进行交换或添加

in the constructor, to swap after paintGL returns, or add

swapBuffers();

paintGL末尾.

at the end of paintGL.

这篇关于用Qt和OpenGL显示一个三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆