Hello,
I read the pixel color and print it to the console. It looks like triangle is not on his place:
main.cpp
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QMouseEvent>
#include <QtOpenGL/QOpenGLBuffer>
#include <QtOpenGL/QOpenGLShaderProgram>
#include <QtOpenGLWidgets/QOpenGLWidget>
#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
class OpenGLWidget : public QOpenGLWidget, private QOpenGLFunctions
{
Q_OBJECT
private:
void initializeGL() override
{
initializeOpenGLFunctions();
glClearColor(0.f, 1.f, 0.f, 1.f);
QString vertexShaderSource =
"attribute vec2 aPosition;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPosition, 0.0, 1.0);\n"
"}\n";
QString fragmentShaderSource =
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"//out vec4 fragColor;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
"}\n";
m_program.addShaderFromSourceCode(QOpenGLShader::ShaderTypeBit::Vertex,
vertexShaderSource);
m_program.addShaderFromSourceCode(QOpenGLShader::ShaderTypeBit::Fragment,
fragmentShaderSource);
m_program.link();
m_program.bind();
float vertPositions[] = {
-0.5f, -0.5f,
0.5f, -0.5f,
0.f, 0.5f
};
m_vertPosBuffer.create();
m_vertPosBuffer.bind();
m_vertPosBuffer.allocate(vertPositions, sizeof(vertPositions));
m_aPositionLocation = m_program.attributeLocation("aPosition");
}
void paintGL() override
{
glClear(GL_COLOR_BUFFER_BIT);
m_program.setAttributeBuffer(m_aPositionLocation, GL_FLOAT, 0, 2);
m_program.enableAttributeArray(m_aPositionLocation);
glDrawArrays(GL_TRIANGLES, 0, 3);
if (m_mouseClicked)
{
// Read the pixel
GLubyte pixel[4];
glReadPixels(m_mouseX, m_mouseY, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
qDebug() << pixel[0] / 255.f << pixel[1] / 255.f << pixel[2] / 255.f;
m_mouseClicked = false;
}
}
void mousePressEvent(QMouseEvent *event) override
{
m_mouseX = event->pos().x();
m_mouseY = height() - event->pos().y() - 1;
m_mouseClicked = true;
update();
}
private:
int m_mouseX;
int m_mouseY;
bool m_mouseClicked = false;
QOpenGLBuffer m_vertPosBuffer;
QOpenGLShaderProgram m_program;
int m_aPositionLocation;
};
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow()
{
setWindowTitle("OpenGL, Qt6, C++");
resize(300, 300);
m_nameLabel = new QLabel("Click on object or background");
m_nameLabel->setSizePolicy(QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed);
OpenGLWidget *openGLWidget = new OpenGLWidget();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(m_nameLabel);
layout->addWidget(openGLWidget);
setLayout(layout);
}
private:
QLabel *m_nameLabel;
};
#include "main.moc"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow w;
w.show();
return app.exec();
}
pro
QT += core gui openglwidgets widgets
win32: LIBS += -lopengl32
CONFIG += c++17
SOURCES += \
main.cpp
TARGET = app
Cross-refs: