【原创】qCustomPlot启用OpenGL

        网上有很多讲qCustomPlot启动OpenGL的文章,有些是很有用的,但也好像没有完全说清楚,现在把我觉得有用的收集起来,并加上一些自己的理解。

1. 下载qCustomPlot

     https://www.qcustomplot.com/

2. 下载freeglut库

     由于qCustomPlot需要调用glut库里的函数,但是glut库比较老旧,而且在实际测试中,也发现一旦new了多个图表控件,当鼠标在几个窗口之间点击的时候,会互相影响,错乱,甚至崩溃的现象。freeglut库是glut的最佳替代版本,更换之后,果然解决了这个问题。

    http://freeglut.sourceforge.net/index.php

 

3. 将"qcustomplot.h和qcustomplot.cpp"添加到自己的工程中,在qcustomplot.cpp最前面加一条头文件引用

#include "qcustomplot.h"

//<Added by jamie 2022.08.29
#include <GL/freeglut.h>
//>

4. 在qcustomplot.cpp文件中搜索 "QCPPaintBufferGlFbo::draw",在“drawImage”之前一行加入如下代码以修复上下文错误

/* inherits documentation from base class */
void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
{
  if (!painter || !painter->isActive())
  {
    qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
    return;
  }
  if (!mGlFrameBuffer)
  {
    qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
    return;
  }

  //<Added by jamie 2022.08.29
  if (QOpenGLContext::currentContext() != mGlContext.data()) {
        mGlContext.data()->makeCurrent(mGlContext.data()->surface());
    }//>

  painter->drawImage(0, 0, mGlFrameBuffer->toImage());
}

5. 在工程.pro中添加以下内容:

        在工程右键"添加库",找到freeglut.lib库文件和头文件,把freeglut.dll文件拷贝到exe所在目录下,注意32位和64位库的目录有区别,由于项目中需要32位库,但该模块将来还想用于64位项目,所以我都给它加入进去,反正也不费电。

Qt +=opengl

DEFINES += QCUSTOMPLOT_USE_OPENGL

//不需要传说中的 Lib += -lopengl32

unix|win32: LIBS += -L$$PWD/../../../bin/Lib/freeglut-MSVC-3.0.0/freeglut/lib/ -lfreeglut
unix|win32: LIBS += -L$$PWD/../../../bin/Lib/freeglut-MSVC-3.0.0/freeglut/lib/x64/ -lfreeglut

INCLUDEPATH += $$PWD/../../../bin/Lib/freeglut-MSVC-3.0.0/freeglut/include
DEPENDPATH += $$PWD/../../../bin/Lib/freeglut-MSVC-3.0.0/freeglut/include

6. 在你代码中设置qCustomPlot开启OpenGl功能,在运行时,看到“应用程序输出”窗口有opengl = true字样,说明启动成功。

ui->customPlot->setOpenGl(true);
qDebug()<<"opengle="<<ui->customPlot->openGl();

 

猜你喜欢

转载自blog.csdn.net/jam12315/article/details/126582996