作者:zhengping4476 | 来源:互联网 | 2023-10-12 17:32
一直比较推崇QT这个界面库,所以打算把osg嵌入到QT里面做一个QWidget的子控件。在查阅了官方的osgViewerQT后,决定写一个子类,同时继承osgViewer::Viewer和QGLWid
一直比较推崇QT这个界面库,所以打算把osg嵌入到QT里面做一个QWidget的子控件。
在查阅了官方的osgViewerQT后,决定写一个子类,同时继承osgViewer::Viewer和QGLWidget,用一个Widget来显示osg的单Viewer的场景。
class OsgQtWidget : public QGLWidget, public osgViewer::Viewer
{
Q_OBJECT
public:
OsgQtWidget(QWidget *parent = 0, const QGLWidget * shareWidget = 0, Qt::WFlags flags = 0);
OsgQtWidget(osgViewer::ViewerBase::ThreadingModel threadingModel = osgViewer::Viewer::SingleThreaded);
~OsgQtWidget();
void setScene();
osg::Camera* createCamera( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false );
virtual void paintGL();
private:
protected:
QTimer timer;
};
其中setScene()的关键代码
osg::Camera *camera = new osg::Camera();
camera = createCamera(0,0,100,100); //创建一个相机,具体实现见下文
this->setCamera( camera ); //使用上述相机
this->setSceneData( osgDB::readNodeFile("feature_geom.earth") ); //加载场景
this->addEventHandler( new osgViewer::StatsHandler );
this->setCameraManipulator( new osgEarth::Util::EarthManipulator() ); //设置漫游器为osgearth的漫游器
//将相机中管理的图形设备提供给QGLWidget当一个部件。
osgQt::GraphicsWindowQt* gw = dynamic_cast( camera->getGraphicsContext() );
QWidget* widget1 = gw->getGLWidget();
QGridLayout* grid = new QGridLayout;
grid->addWidget( widget1, 0, 0 );
this->setLayout( grid );
//通过定义一个Timer使QWidge实时(每10毫秒)更新窗口,也即触发paintGL事件,在paintGL事件中,调用frame方法来重绘帧。
connect( &timer, SIGNAL(timeout()), this, SLOT(update()) );
timer.start( 10 );
createCarema的代码
如上图所示,在一个Viewer中,相机拍摄的内容是用图形设备(GraphicsContext)做为载体来显示渲染结果
osg::Camera* OsgQtWidget::createCamera( int x, int y, int w, int h, const std::string& name, bool windowDecoration)
{
osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
//定义渲染窗口的属性此窗口可以被各个平台实现。
osg::ref_ptr traits = new osg::GraphicsContext::Traits;
traits->windowName = name;
traits->windowDecoration = windowDecoration;
traits->x = x;
traits->y = y;
traits->width = w;
traits->height = h;
traits->doubleBuffer = true;
traits->alpha = ds->getMinimumNumAlphaBits();
traits->stencil = ds->getMinimumNumStencilBits();
traits->sampleBuffers = ds->getMultiSamples();
traits->samples = ds->getNumMultiSamples();
osg::ref_ptr camera = new osg::Camera;
camera->setGraphicsContext( new osgQt::GraphicsWindowQt(traits.get()) );
//设置相机所看到的背景颜色
camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
//设置视口
camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
//设置投影矩阵为透视投影
camera->setProjectionMatrixAsPerspective(
30.0f, static_cast(traits->width)/static_cast(traits->height), 1.0f, 10000.0f );
return camera.release();
}