天天看点

Qt加载Osg的新方式osgQOpenGL简介一、概述二、运行效果图三、简要步骤四、Widget.h代码五、Widget.cpp代码六、Main.cpp代码七、TestOsgQt.pro代码

一、概述

Qt加载Osg的老方式是使用osg3.4以及以前的某些版本中提供的osgQt项目加载osg,不过这种方式,在3.6等新版本中不再支持,更改起来比较麻烦,osg::GraphicsContext类不再提供osg::GraphicsContext::setWindowingSystemInterface接口函数,无法编译成功。不过目前有个替代方案,使用osgQOpenGL的osgQOpenGLWidget类进行三维模型的加载,下载地址为:

https://github.com/OpenSceneGraph/osgQt

下面是使用osgQOpenGLWidget加载osg的演示例子。

二、运行效果图

Qt加载Osg的新方式osgQOpenGL简介一、概述二、运行效果图三、简要步骤四、Widget.h代码五、Widget.cpp代码六、Main.cpp代码七、TestOsgQt.pro代码

三、简要步骤

  1. 创建osgQOpenGLWidget并加入到控件布局中
  2. 响应osgQOpenGLWidget的initialized信号,设置一个漫游操作器,读取osg模型文件并加入到场景节点中。

四、Widget.h代码

#ifndef WIDGET_H

#define WIDGET_H

#include <QWidget>

class Widget : public QWidget

{

    Q_OBJECT

public:

    Widget(QWidget *parent = 0);

    ~Widget();

private slots:

void initOsg();

};

#endif // WIDGET_H

五、Widget.cpp代码

#include "widget.h"

#include <osgQOpenGL/osgQOpenGLWidget>

#include <QBoxLayout>

#include <osgDB/ReadFile>

#include <osgViewer/Viewer>

#include <osgUtil/Optimizer>

#include <osgGA/TrackballManipulator>

#include <QLabel>

Widget::Widget(QWidget *parent)

    : QWidget(parent)

{

resize(400, 300);

QHBoxLayout *pLayout = new QHBoxLayout(this);

pLayout->setMargin(0);

osgQOpenGLWidget *pOsgW = new osgQOpenGLWidget;

pLayout->addWidget(pOsgW);

connect(pOsgW, SIGNAL(initialized()), this, SLOT(initOsg()));

}

Widget::~Widget()

{

}

void Widget::initOsg()

{

osgViewer::Viewer *pViewer = ((osgQOpenGLWidget *)sender())->getOsgViewer();

pViewer->setCameraManipulator(new osgGA::TrackballManipulator());

osg::Node *pNode = osgDB::readNodeFile("boxman.osg");

osgUtil::Optimizer optimizer;

optimizer.optimize(pNode);

pViewer->setSceneData(pNode);

}

六、Main.cpp代码

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])

{

    QApplication a(argc, argv);

    Widget w;

    w.show();

    return a.exec();

}

七、TestOsgQt.pro代码

QT       += core gui widgets

TARGET = TestOsgQt

TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

CONFIG += c++11

SOURCES += \

        main.cpp \

        widget.cpp

HEADERS += \

        widget.h

OsgDir = C:\r

CONFIG(release, debug|release) {

LIBS += -L$${OsgDir}/lib/ -losgQOpenGL -losgDB -losgViewer -losg -losgUtil -losgGA

} else {

LIBS += -L$${OsgDir}/lib/ -losgQOpenGLd -losgDBd -losgViewerd -losgd -losgUtild -losgGAd

}

INCLUDEPATH += $${OsgDir}/include

DEPENDPATH += $${OsgDir}/include

继续阅读