c++ - Qt 5.3. QWidget direct painting with OpenGL -
good day. there ways paint qwidget
-based window without qpainter
. try use raw opengl drawing following code:
1) main function:
int main(int argc, char* argv[]) { qapplication app(argc, argv); glwindow* window = new glwindow; window->setminimumsize(200, 200); window->initializeglcontext(); window->show(); return app.exec(); }
glwindow inhereted qmainwindow
. use glew library in order work opengl
. below simplified version of code without error handling , stupid program flow.
namespace { glfloat vertices[] = { 0.0f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f }; const char* vertexshadersource = "in vec2 position;" "void main() {" "gl_position = vec4(position, 0.0, 1.0); }"; const char* fragmentshadersource = "out vec4 outcolor;" "void main() {" "outcolor = vec4(1.0, 0.0, 0.0, 1.0); }"; } glwindow::glwindow() { setattribute(qt::wa_paintonscreen, true); } void glwindow::initializeglcontext() { pixelformatdescriptor pfd = { sizeof(pixelformatdescriptor), 1, pfd_draw_to_window | pfd_support_opengl | pfd_doublebuffer, pfd_type_rgba, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 8, 0, pfd_main_plane, 0, 0, 0, 0 }; hdc hdc = getdc((hwnd)winid()); int windowpixelformat = choosepixelformat(hdc, &pfd); setpixelformat(hdc, windowpixelformat, &pfd); hglrc hglrc = wglcreatecontext(hdc); wglmakecurrent(hdc, hglrc); } qpaintengine* glwindow::paintengine() const { return 0; } void glwindow::paintevent(qpaintevent *) { glewinit(); gluint vao; glgenvertexarrays(1, &vao); glbindvertexarray(vao); gluint vbo; glgenbuffers(1, &vbo); glbindbuffer(gl_array_buffer, vbo); glbufferdata(gl_array_buffer, sizeof(vertices), vertices, gl_static_draw); gluint vertexshader = glcreateshader(gl_vertex_shader); glshadersource(vertexshader, 1, &vertexshadersource, null); glcompileshader(vertexshader); gluint fragmentshader = glcreateshader(gl_fragment_shader); glshadersource(fragmentshader, 1, &fragmentshadersource, null); glcompileshader(fragmentshader); gluint shaderprogram = glcreateprogram(); glattachshader(shaderprogram, vertexshader); glattachshader(shaderprogram, fragmentshader); gllinkprogram(shaderprogram); gluseprogram(shaderprogram); glint posattrib = glgetattriblocation(shaderprogram, "position"); glenablevertexattribarray(posattrib); glvertexattribpointer(posattrib, 2, gl_float, gl_false, 0, 0); glclearcolor(0.0f, 0.0f, 0.0f, 1.0f); glclear(gl_color_buffer_bit); gldrawarrays(gl_triangles, 0, 3); swapbuffers(getdc((hwnd)winid())); }
after program execution have black screen without triangle. i'm novice in qt
, if have suggestions going wrong, please share them me.
best regards.
you should use baseclass qglwidget
, override paintgl
instead.
Comments
Post a Comment