当前位置: 代码迷 >> 综合 >> J_8 绘图与GraphicsView、QGraphicsScene、QGraphicsProxyWidget
  详细解决方案

J_8 绘图与GraphicsView、QGraphicsScene、QGraphicsProxyWidget

热度:79   发布时间:2024-01-29 18:20:19.0

1、绘图可以简单地理解成有一个视图GraphicsView,在这个视图中可以加载多个场景QGraphicsScene,多个场景中加载多个QGraphicsItem对象;

2、QGraphicsProxyWidget的作用是为在场景中嵌入QWidget,例如QPushButton, QFontComboBox,QFileDialog等,提供一个代理层,QGraphicsProxyWidget也是一个QGraphicsItem对象;

3、QGLWidget是一个用来渲染OpenGL图形的控件,它将OpenGL图形集成到一个Qt应用中,用法是GraphicsView.setViewport(QGLWidget)即可;

4、如实例所示,创建一个场景类Scene,继承自QGraphicsScene;

Scene.h中:
class Scene : public QGraphicsScene
{Q_OBJECT
public:Scene();~Scene();
};
Scene.cpp中:
Scene::Scene()
{setSceneRect(0,0,600,400);setBackgroundBrush(Qt::blue);
}
Scene::~Scene()
{
}

 5、如实例所示,创建一个控件代理类ProxyWidget,继承自QGraphicsProxyWidget;

ProxyWidget.h中:
class ProxyWidget : public QGraphicsProxyWidget
{
public:ProxyWidget();
protected:void resizeEvent(QGraphicsSceneResizeEvent *event) override;void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
};
ProxyWidget.cpp中:
void ProxyWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
{setCacheMode(QGraphicsItem::NoCache);setCacheMode(QGraphicsItem::ItemCoordinateCache);QGraphicsProxyWidget::resizeEvent(event);
}
void ProxyWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{painter->setRenderHint(QPainter::Antialiasing, false);QGraphicsProxyWidget::paint(painter, option, widget);}
void ProxyWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{Form2 *mform2 = new Form2;this->setWidget(mform2);
}

在这里通常要重写resizeEvent和 paint方法,本例中我们要实现双击这个嵌入的控件,从而更换这个嵌入的控件,所以加了一个重写方法 mouseDoubleClickEvent;mouseDoubleClickEvent方法中实现了此代理层更换Form控件为Form2控件;

6、在main.cpp中添加代码:

int main(int argc, char *argv[])
{QApplication a(argc, argv);Form mform;ProxyWidget *proxy = new ProxyWidget;proxy->setWidget(&mform);proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache);proxy->setZValue(1e30);proxy->setVisible(true);Scene scene;scene.addItem(proxy);QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers));widget->makeCurrent();QGraphicsView view;view.setViewport(widget);view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate);view.setScene(&scene);view.show();return a.exec();
}

此代码完成的是,将Form控件赋加给代理类,这个代理类赋加到场景类,场景类由视图渲染显示;

需要查看运行视频或完整源代码,请到www.toutiao.com/i6850496775749386763/链接评论区写上你的邮箱