qt qgraphicsview自定义绘图
时间: 2023-09-21 12:06:54 浏览: 84
自定义绘图
在Qt中,可以使用QGraphicsView来显示自定义绘图。以下是一个简单的例子:
1. 创建一个自定义的QGraphicsScene类,继承自QGraphicsScene,并重写其drawBackground()方法。在该方法中,可以绘制背景图形。
```cpp
class CustomScene : public QGraphicsScene
{
public:
CustomScene(QObject* parent = nullptr) : QGraphicsScene(parent) {}
protected:
void drawBackground(QPainter* painter, const QRectF &rect) override
{
// 绘制背景图形
painter->setBrush(Qt::gray);
painter->drawRect(rect);
}
};
```
2. 创建一个QGraphicsView对象,并设置其scene为自定义QGraphicsScene对象。
```cpp
QGraphicsView* view = new QGraphicsView();
CustomScene* scene = new CustomScene();
view->setScene(scene);
```
3. 在需要绘制的地方,使用QGraphicsItem的派生类来绘制图形,例如QGraphicsRectItem。
```cpp
QGraphicsRectItem* rect = new QGraphicsRectItem(0, 0, 100, 100);
rect->setBrush(Qt::blue);
scene->addItem(rect);
```
4. 显示QGraphicsView。
```cpp
view->show();
```
完整的代码如下:
```cpp
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
class CustomScene : public QGraphicsScene
{
public:
CustomScene(QObject* parent = nullptr) : QGraphicsScene(parent) {}
protected:
void drawBackground(QPainter* painter, const QRectF &rect) override
{
// 绘制背景图形
painter->setBrush(Qt::gray);
painter->drawRect(rect);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView* view = new QGraphicsView();
CustomScene* scene = new CustomScene();
view->setScene(scene);
QGraphicsRectItem* rect = new QGraphicsRectItem(0, 0, 100, 100);
rect->setBrush(Qt::blue);
scene->addItem(rect);
view->show();
return a.exec();
}
```
阅读全文