一、概述
Qt加载Osg的老方式是使用osg3.4以及以前的某些版本中提供的osgQt项目加载osg,不过这种方式,在3.6等新版本中不再支持,更改起来比较麻烦,由于osg::GraphicsContext类不再提供osg::GraphicsContext::setWindowingSystemInterface接口函数,导致不能将osgQt项目编译成功。不过目前有个替代方案,使用osgQOpenGL的osgQOpenGLWidget类进行三维模型的加载,下载地址为:
https://github.com/OpenSceneGraph/osgQt
下面是使用osgQOpenGLWidget从osgEarth的.earth配置文件加载三位数字地球的演示例子。
二、运行效果图
三、简要步骤
-
创建osgQOpenGLWidget类对象并加入到控件布局中
-
响应osgQOpenGLWidget的initialized信号,设置一个漫游操作器,读取osgEarth的.earth模型文件并加入到场景节点中。
四、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 <osgEarth/TerrainOptions>
#include <osgEarth/Config>
#include <osgEarth/MapNodeOptions>
#include <osgEarth/MapNode>
#include <osgEarthUtil/EarthManipulator>
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());
// pViewer->setCameraManipulator(new osgEarth::Util::EarthManipulator());
// osg::Node *pNode = osgDB::readNodeFile("boxman.osg");
osgEarth::Config c;
c.add("elevation_smoothing", false);
osgEarth::TerrainOptions to(c);
osgEarth::MapNodeOptions defMNO;
defMNO.setTerrainOptions(to);
osg::ref_ptr<osgDB::Options> options = new osgDB::Options();
options->setPluginStringData("osgEarth.defaultOptions", defMNO.getConfig().toJSON());
osg::Node *pNode = osgDB::readNodeFile("simple.earth", options);
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 -lOpenThreads -losgEarth -losgEarthUtil
} else {
LIBS += -L$${OsgDir}/lib/ -losgQOpenGLd -losgDBd -losgViewerd -losgd -losgUtild -losgGAd -lOpenThreadsd -losgEarthd -losgEarthUtild
}
INCLUDEPATH += $${OsgDir}/include
DEPENDPATH += $${OsgDir}/include