osg嵌入Qt窗口完整代码的一个示例:
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTimer>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
class OSGWidget : public QWidget
{
public:
OSGWidget(QWidget* parent = nullptr)
: QWidget(parent, Qt::Widget)
, _viewer(new osgViewer::Viewer())
{
// Create a widget to contain the osg viewer
QWidget* widget = QWidget::createWindowContainer(_viewer->setUpViewerAsEmbeddedInWindow(0, 0, width(), height()));
// Set up the camera manipulator
_viewer->setCameraManipulator(new osgGA::TrackballManipulator);
// Load a model to display
osg::ref_ptr<osg::Node> scene = osgDB::readNodeFile("cow.osg");
if (scene)
{
_viewer->setSceneData(scene);
}
// Connect the timer to the update loop
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &OSGWidget::update);
timer->start(10);
// Add the widget to the layout
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(widget);
setLayout(layout);
}
void update()
{
_viewer->frame();
}
private:
osg::ref_ptr<osgViewer::Viewer> _viewer;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
// Create a main window with an OSG widget and a button
QWidget mainWindow;
QVBoxLayout* layout = new QVBoxLayout(&mainWindow);
layout->addWidget(new OSGWidget(&mainWindow));
layout->addWidget(new QPushButton("Button", &mainWindow));
mainWindow.setWindowTitle("OSG in Qt");
mainWindow.show();
return app.exec();
}
此代码创建一个OSGWidget
类,该类继承自QWidget
,并使用osg在其中显示一个模型。然后,将该类放入Qt布局中,并在同一窗口中添加一个按钮。
这段代码的关键是使用QWidget::createWindowContainer
函数将osg视图嵌入到qt窗口中。然后,使用QTimer
定期调用osg的frame()
函数更新场景。