QPainter默认使用CPU进行渲染,如果要使用GPU进行渲染,可以使用OpenGL来实现。
- 创建一个QGLWidget,并设置其格式为QGLFormat::defaultFormat()。
#include <QtGui/QApplication>
#include <QtOpenGL/QGLWidget>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGLFormat format;
format.setVersion(3, 3);
format.setProfile(QGLFormat::CoreProfile);
QGLWidget widget(format);
widget.show();
return app.exec();
}
- 在widget中重载paintEvent函数,在其中创建一个QPainter对象,并通过beginNativePainting和endNativePainting函数来绘制OpenGL图形。
void MyWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.beginNativePainting();
// 使用OpenGL进行渲染
glClearColor(0.2f, 0.3f, 0.4f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(1.f, 0.f, 0.f);
glVertex2f(-1.f, -1.f);
glColor3f(0.f, 1.f, 0.f);
glVertex2f(1.f, -1.f);
glColor3f(0.f, 0.f, 1.f);
glVertex2f(0.f, 1.f);
glEnd();
painter.endNativePainting();
}
注意:在使用OpenGL时需要包含头文件
#include <QtGui/QOpenGLFunctions>
class MyOpenGLFunctions : public QOpenGLFunctions
{
public:
MyOpenGLFunctions() { initializeOpenGLFunctions(); }
};
class MyWidget : public QGLWidget, protected MyOpenGLFunctions
{
// ...
};
这样,在paintEvent中就可以使用所有的OpenGL函数了。