Skip to content

Instantly share code, notes, and snippets.

@8Observer8
Last active October 9, 2022 14:36
Show Gist options
  • Save 8Observer8/27495ff717e2df3789b1a1daaa4bb5ed to your computer and use it in GitHub Desktop.
Save 8Observer8/27495ff717e2df3789b1a1daaa4bb5ed to your computer and use it in GitHub Desktop.
Very Simple Triangle using OpenGL2, Qt6, and C++
// To run on laptops:
#ifdef _WIN32
#include <windows.h>
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
#endif
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QSurfaceFormat>
#include <QtOpenGL/QOpenGLBuffer>
#include <QtOpenGL/QOpenGLShaderProgram>
#include <QtOpenGLWidgets/QOpenGLWidget>
#include <QtWidgets/QApplication>
class Widget : public QOpenGLWidget, QOpenGLFunctions
{
public:
Widget()
{
setFixedSize(QSize(270, 270));
setWindowTitle("OpenGL2 Qt6 C++");
}
private:
QOpenGLShaderProgram m_program;
QOpenGLBuffer m_vertexPositionBuffer;
int m_aPositionLocation;
private:
void initializeGL() override
{
initializeOpenGLFunctions();
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
const char *vertexShaderSource =
"attribute vec3 aPosition;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPosition, 1.0);"
"}\n";
const char *fragmentShaderSource =
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);"
"}\n";
m_program.create();
m_program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
m_program.addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
m_program.bind();
m_aPositionLocation = m_program.attributeLocation("aPosition");
float vertexPositions[] = {
-0.5f, -0.5f, 0.f,
0.5f, -0.5f, 0.f,
0.f, 0.5f, 0.f
};
m_vertexPositionBuffer.create();
m_vertexPositionBuffer.bind();
m_vertexPositionBuffer.allocate(vertexPositions, sizeof(vertexPositions));
m_program.setAttributeBuffer(m_aPositionLocation, GL_FLOAT, 0, 3);
m_program.enableAttributeArray(m_aPositionLocation);
}
void resizeGL(int w, int h) override
{
glViewport(0, 0, w, h);
}
void paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
};
int main(int argc, char *argv[])
{
// To run from CMD to print messages:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
QApplication app(argc, argv);
Widget w;
QSurfaceFormat format;
format.setSamples(8);
w.setFormat(format);
w.show();
return app.exec();
}
# Build commands for CMD:
# qmake -makefile
# mingw32-make
# "./release/app"
QT += core gui openglwidgets
win32: LIBS += -lopengl32
CONFIG += c++11
SOURCES += \
main.cpp
TARGET = app
@8Observer8
Copy link
Author

Screenshot:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment