美好的一天。
有没有办法在没有QWidget
的情况下绘制基于QPainter
的窗口。我尝试使用原始OpenGL绘制以下代码:
1)主要功能:
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来自QMainWindow
。我使用glew库来处理OpenGL
。下面是代码的简化版本,没有错误处理和愚蠢的程序流程。
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()));
}
程序执行后,我所拥有的是没有三角形的黑屏。我是Qt
的新手,如果您有任何建议,请与我分享。
最好的问候。